How can I change the x-axis labels in a Python plot? - python

I have this code :
import numpy as np
import pylab as plt
a = np.array([1,2,3,4,5,6,7,8,9,10])
b = np.exp(a)
plt.plot(a,b,'.')
plt.show()
The code works fine, but I need to modify the x-axis labels of the plot.
I would like the x-axis labels to be all powers of 10 according to the a axis inputs. for the example code, it would be like [10^1, 10^2, ..., 10^10].
I would appreciate any suggestions.
Thank you !

import numpy as np
import pylab as plt
a = np.array([1,2,3,4,5,6,7,8,9,10])
# this is it, but better use floats like 10.0,
# a integer might not hold values that big
b = 10.0 ** a
plt.plot(a,b,'.')
plt.show()

This code probably is what you need:
import numpy as np
import pylab as plt
a = np.asarray([1,2,3,4,5,6,7,8,9,10])
b = np.exp(a)
c = np.asarray([10**i for i in a])
print(list(zip(a,c)))
plt.xticks(a, c)
plt.plot(a,b,'.')
plt.show()
By using plt.xtick() you can customize your x-label of plot. I also replaced 10^i with 10**i.

Related

Plotting a bar chart

I have an imported excel file in python and want to create a bar chart.
In the bar chart, I want the bars to be separated by profit, 0-10, 10-20, 20-30...
How do I do this?
this is one of the things I have tried:
import NumPy as np
import matplotlib.pyplot as plt
%matplotlib inline
df.plot(kind="bar",x="profit", y="people")
df[df.profit<=10]
plt.show()
and:
df[df.profit range (10,20)]
It is a bit difficult to help you better without a sample of your data, but I constructed a dataset randomly that should have the shape of yours, so that this solution can hopefully be useful to you:
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# For random data
import random
%matplotlib inline
df = pd.DataFrame({'profit':[random.choice([i for i in range(100)]) for x in range(100)], 'people':[random.choice([i for i in range(100)]) for x in range(100)]})
display(df)
out = pd.cut(df['profit'], bins=[x*10 for x in range(10)], include_lowest=True)
ax = out.value_counts(sort=False).plot.bar(rot=0, color="b", figsize=(14,4))
plt.xlabel("Profit")
plt.ylabel("People")
plt.show()
I had a look at another question on here (Pandas bar plot with binned range) and there they explained how this issue can be solved.
Hope it helps :)

Difference between specified and measured colours, matplotlib colormap

I'm having trouble replicating an old colormap I've used in matplotlib. It seems as if it was the default colormap because in the original code, no colormap was specified.
So looking at the old figure I made I've measured the colours from the colorbar using gpick. I've inputted these into a custom colormap as follows:
blue_red1 = LinearSegmentedColormap.from_list('mycmap', [
(0, '#6666de'),
(0.1428, '#668cff'),
(0.2856, '#66d9ff'),
(0.4284, '#92ffce'),
(0.5712, '#d0ff90'),
(0.714, '#ffe366'),
(0.8568, '#ff9b66'),
(1, '#db6666')])
CS = plt.contourf(H, temps, diff_list, cmap=blue_red1)
plt.savefig('out.png')
Yet when I measure the output colours with gpick again they have different hex values (and I can tell they're different).
What could be causing this?
The original I'm trying to replicate, and the output from the custom colour map are linked below:
You may get much closer to the desired result using the following.
The logic is that each color in the colorbar is the value corresponding to the mean of its interval.
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
X,Y=np.meshgrid(np.linspace(0,1),np.linspace(0,1) )
Z = X+Y
blue_red1 = LinearSegmentedColormap.from_list('mycmap', [
(0.0000, '#6666de'),
(0.0625, '#6666de'),
(0.1875, '#668cff'),
(0.3125, '#66d9ff'),
(0.4375, '#92ffce'),
(0.5625, '#d0ff90'),
(0.6875, '#ffe366'),
(0.8125, '#ff9b66'),
(0.9375, '#db6666'),
(1.0000, '#db6666')])
CS = plt.contourf(X,Y,Z, cmap=blue_red1)
plt.colorbar()
plt.show()
The other option is to use a ListedColormap. This gives the accurate colors.
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
X,Y=np.meshgrid(np.linspace(0,1),np.linspace(0,1) )
Z = X+Y
blue_red1 = ListedColormap(['#6666de','#668cff','#66d9ff','#92ffce','#d0ff90',
'#ffe366','#ff9b66','#db6666'],'mycmap')
CS = plt.contourf(X,Y,Z, cmap=blue_red1)
plt.colorbar()
plt.show()

add legend to numpy array in matplot lib

I am plotting 2D numpy arrays using
import numpy as np
import matplotlib.pyplot as plt
x = np.array([1,2,3])
y = np.array([[2,2.2,3],[1,5,1]])
plt.plot(x,y.T[:,:])
plt.legend()
plt.show()
I want a legend that tells which line belongs to which row. Of course, I realize I can't give it meaningful names, but I need some sort of unique label for the line without running through loop.
import numpy as np
import matplotlib.pyplot as plt
import uuid
x = np.array([1,2,3])
y = np.array([[2,2.2,3],[1,5,1]])
fig, ax = plt.subplots()
lines = ax.plot(x,y.T[:,:])
ax.legend(lines, [str(uuid.uuid4())[:6] for j in range(len(lines))])
plt.show()
(This is off of the current mpl master branch with a preview of the 2.0 default styles)

plotting multiple histograms in grid

I am running following code to draw histograms in 3 by 3 grid for 9 varaibles.However, it plots only one variable.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
def draw_histograms(df, variables, n_rows, n_cols):
fig=plt.figure()
for i, var_name in enumerate(variables):
ax=fig.add_subplot(n_rows,n_cols,i+1)
df[var_name].hist(bins=10,ax=ax)
plt.title(var_name+"Distribution")
plt.show()
You're adding subplots correctly but you call plt.show for each added subplot which causes what has been drawn so far to be shown, i.e. one plot. If you're for instance plotting inline in IPython you will only see the last plot drawn.
Matplotlib provides some nice examples of how to use subplots.
Your problem is fixed like:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
def draw_histograms(df, variables, n_rows, n_cols):
fig=plt.figure()
for i, var_name in enumerate(variables):
ax=fig.add_subplot(n_rows,n_cols,i+1)
df[var_name].hist(bins=10,ax=ax)
ax.set_title(var_name+" Distribution")
fig.tight_layout() # Improves appearance a bit.
plt.show()
test = pd.DataFrame(np.random.randn(30, 9), columns=map(str, range(9)))
draw_histograms(test, test.columns, 3, 3)
Which gives a plot like:
In case you don't really worry about titles, here's a one-liner
df = pd.DataFrame(np.random.randint(10, size=(100, 9)))
df.hist(color='k', alpha=0.5, bins=10)

matplotlib 3d wireframe plot

Right, so I've got a list of x values, y values and z values (which I think I converted into arrays?) which I want to make a surface plot, but it's not working.
Here's what I'm trying to do, you can ignore most of the code as it is pretty irrelevant - just look at the end where I have xdis, ydis and dist and where I'm trying to plot atm I'm getting ValueError: need more than 1 value to unpack :(. Help much appreciated.
from math import *
from numpy import *
import pylab
def sweep (v,p,q,r,s):
a=.98
for i in range (1, len(v)-1):
for j in range (1, len(v)-1):
c =0.0
if i==p and j==q: c =1.0
if i==r and j==s: c= -1.0
v[i,j]=(v[i -1,j]+v[i+1,j]+v[i,j -1]+v[i,j+1]+c-a*v[i,j])/(4-a)
def main():
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import matplotlib.pyplot as plt
ydis=[]
xdis=[]
resis=[]
for j in range(2,18):
for i in range(2,18):
v= zeros ((20,20),float )
p=q=9
r=i
s=j
dv =1.0e10
lastdv =0
count =0
while (fabs(dv - lastdv)>1.0e-7*fabs(dv)):
lastdv =dv
sweep(v,p,q,r,s)
dv=v[p,q]-v[r,s]
resis.append(dv)
xdis.append(r-p)
ydis.append(s-q)
X=array(xdis)
Y=array(ydis)
Z=array(resis)
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_wireframe(X,Y,Z)
plt.show()
main()
plot_wireframe expects three 2D-arrays (X,Y,Z) as input. So,
after:
X=np.array(xdis)
Y=np.array(ydis)
Z=np.array(resis)
add:
X=X.reshape((-1,16))
Y=Y.reshape((-1,16))
Z=Z.reshape((-1,16))
It doesn't seem like the "sweep" function is modifying 'v' so you're getting an empty list.

Categories

Resources