I created the following histogram from the frequeny of each class in a training set
The label of each class is too long and is similar to
Speed limit (20km/h)
Can I place each label on the bar itself?
Maybe something like this?
import numpy as np
import matplotlib.pyplot as plt
N=5
xlabel = ["Speed limit ("+str(i)+"km/h)" for i in range(0,N)]
xs = np.arange(0,7,1.5)
ys = [8,6,10,7,9]
width = 0.3*np.ones(N)
fig, ax = plt.subplots()
bars = ax.bar(xs, ys, width, color='k',alpha=0.3)
plt.xticks(xs, xlabel,rotation=270)
for i,bar in enumerate(bars):
height = bar.get_height()
ax.text(bar.get_x() + bar.get_width()/2., 0.1*height,
'%s' % xlabel[i],rotation=90,ha='center', va='bottom')
plt.show()
To change it to horizontal bar plot:
import numpy as np
import matplotlib.pyplot as plt
N = 5
xlabel = ["Speed limit ("+str(i)+"km/h)" for i in range(0,5)]
xs = np.arange(0,5)/2
ys = [8,6,10,7,9]
width = 0.3*np.ones(N)
fig, ax = plt.subplots()
bars = ax.barh(xs, ys, width, color='k',alpha=0.3)
plt.xticks([])
for i,bar in enumerate(bars):
height = bar.get_height()
ax.text(bar.get_x()+3, bar.get_y()+bar.get_height()/3,
'%s' % xlabel[i],rotation=0,ha='center', va='bottom')
plt.tight_layout()
plt.show()
Related
I plotting a Heatmap with the code bellow, it contains 6 columns and 40 rows so when I plot the heatmap its looks like a narrow column figure:
import numpy as np
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
data = pd.read_csv('X.csv')
x = data.drop(['P'],1)
y = data['P']
Performance_Indices = y.to_list()
Columns= ["AMSR1", "AMSR2", "AMSR3",
"SMAPL3", "SMAPL4", "GLDAS"]
def heatmap(data, row_labels, col_labels, ax=None,
cbar_kw={}, cbarlabel="", **kwargs):
if not ax:
ax = plt.gca()
im = ax.imshow(data, **kwargs)
cbar = ax.figure.colorbar(im, ax=ax, **cbar_kw)
cbar.ax.set_ylabel(cbarlabel, rotation=90, va="bottom", fontsize=10,
fontweight="bold", labelpad=20)
ax.set_xticks(np.arange(data.shape[1]))
ax.set_yticks(np.arange(data.shape[0]))
ax.set_xticklabels(col_labels, fontsize=10, fontweight="bold")
ax.set_yticklabels(row_labels, fontsize=10, fontweight="bold")
ax.tick_params(top=False, bottom=True,
labeltop=False, labelbottom=True)
plt.setp(ax.get_xticklabels(), rotation=90, ha="right",
rotation_mode="anchor")
for edge, spine in ax.spines.items():
spine.set_visible(False)
ax.set_xticks(np.arange(data.shape[1]+1)-.5, minor=True)
ax.set_yticks(np.arange(data.shape[0]+1)-.5, minor=True)
return im, cbar
def annotate_heatmap(im, data=None, valfmt="{x:.2f}",
textcolors=["black", "white"],
threshold=None, **textkw):
if not isinstance(data, (list, np.ndarray)):
data = im.get_array()
if threshold is not None:
threshold = im.norm(threshold)
else:
threshold = im.norm(data.max())/2.
kw = dict(horizontalalignment="center",
verticalalignment="center")
kw.update(textkw)
if isinstance(valfmt, str):
valfmt = matplotlib.ticker.StrMethodFormatter(valfmt)
texts = []
for i in range(data.shape[0]):
for j in range(data.shape[1]):
kw.update(color=textcolors[int(im.norm(data[i, j]) > threshold)])
text = im.axes.text(j, i, valfmt(data[i, j], None), **kw)
texts.append(text)
return texts
fig, ax = plt.subplots()
im, cbar = heatmap(x, Performance_Indices, farmers, ax=ax,
cmap="jet", cbarlabel="Normalized Value")
ax.set_xlabel('Predictive models', fontsize=15, fontweight="bold", labelpad=10)
ax.set_ylabel('Performance Index', fontsize=15, fontweight="bold", labelpad=10)
ax.set_title("b)", fontweight="bold", pad=20, fontsize=15)
But the figure is look like bellow:
HOW CAN I ADJUST THE CELL SIZE SO THAT THE CELLS CAN BE BIGGER, DECIMAL NUMBER CAN BE APPEAR AND THE PLOT LOOK LIKE SOMETHING DECENT!!
Since I do not have your data and therefore can not run your code. I just wrote the following which should solve your problem:
import numpy as np
import matplotlib.pyplot as plt
img = np.random.randint(0,10,(100,100))
# here you can set the figure size
fig,ax = plt.subplots(figsize=(20,20))
# plot somehting - here an image
ax.imshow(img,origin='lower')
# here you can set the aspect ratio
ax.set_aspect(aspect=0.5)
plt.show()
I want to plot a white plot with two axes, show it to the user, then add a line to the white plot with two axes, show it to the user, then add some dot to the line, then show it to the user. How can I do this without copying the code again and again?
What I'm doing now is in the first code chunk
import math
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline
fig = plt.figure(figsize=(5,5))
ax = plt.axes()
ax.set_xlabel('cat')
ax.set_ylabel('dog')
plt.title("Set of 2 animals")
plt.show()
then in the second code chunk
fig = plt.figure(figsize=(5,5))
ax = plt.axes()
x = np.linspace(0, 1.0, 1000)
ax.plot(x, 1.0-x,zorder = 0)
ax.set_xlabel('cat')
ax.set_ylabel('dog')
plt.title("Set of 2 animals")
plt.show()
then in the third code chunk
fig = plt.figure(figsize=(5,5))
ax = plt.axes()
x = np.linspace(0, 1.0, 1000)
ax.plot(x, 1.0-x,zorder = 0)
ax.set_xlabel('cat')
ax.set_ylabel('dog')
plt.title("Set of 2 animals")
p0 = 0.5
p1 = 0.5
color = "blue"
textd =0.05
ax.scatter([p0],[p1], color = color,zorder=1)
ax.text(p0+textd, p1+textd, 'tiger',color = color,zorder =2)
plt.show()
What I'm looking for is things like in the first code chunk
import math
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline
fig = plt.figure(figsize=(5,5))
ax = plt.axes()
ax.set_xlabel('cat')
ax.set_ylabel('dog')
plt.title("Set of 2 animals")
plt.show()
then in the second code chunk
add line directly without duplicating the code for making axes
plt.show()
then in the third code chunk
add point directly without duplicating the code for making axes and lines
plt.show()
Update: I actually figured out the answer.
def plot(step):
fig = plt.figure(figsize=(5,5))
ax = plt.axes()
ax.set_xlabel('cat')
ax.set_ylabel('dog')
plt.title("Set of 2 animals")
if step>=1:
x = np.linspace(0, 1.0, 1000)
ax.plot(x, 1.0-x,zorder = 0)
if step>=2:
p0 = 0.5
p1 = 0.5
color = "blue"
textd =0.05
ax.scatter([p0],[p1], color = color,zorder=1)
ax.text(p0+textd, p1+textd, 'tiger',color = color,zorder =2)
plot.show()
should be able to solve the problem.
I want to plot some data x and y in which I need the marker size to depend on a third array z. I could plot them separately (i.e., scatter x and y with size = z, and errorbar without marker, fmc = 'none') and this solves it. The problem is that I need the legend to show the errorbar AND the dot, together:
and not
Code is here with some made-up data:
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(1,10,100)
y = 2*x
yerr = np.random(0.5,1.0,100)
z = np.random(1,10,100)
fig, ax = plt.subplots()
plt.scatter(x, y, s=z, facecolors='', edgecolors='red', label='Scatter')
ax.errorbar(x, y, yerr=yerr, xerr=0, fmt='none', mfc='o', color='red', capthick=1, label='Error bar')
plt.legend()
plt.show()
which produces the legend I want to avoid:
In errorbar the argumentmarkersizedoes not accept arrays asscatter` does.
The idea is usually to use a proxy to put into the legend. So while the errorbar in the plot may have no marker, the one in the legend has a marker set.
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(1,10,11)
y = 2*x
yerr = np.random.rand(11)*5
z = np.random.rand(11)*2+5
fig, ax = plt.subplots()
sc = ax.scatter(x, y, s=z**2, facecolors='', edgecolors='red')
errb = ax.errorbar(x, y, yerr=yerr, xerr=0, fmt='none',
color='red', capthick=1, label="errorbar")
proxy = ax.errorbar([], [], yerr=[], xerr=[], marker='o', mfc="none", mec="red",
color='red', capthick=1, label="errorbar")
ax.legend(handles=[proxy], labels=["errorbar"])
plt.show()
I have a matrix that I want to show (np.asarray(vectors).T) and so far everything works except that the image is having way to much padding below the bottom x-axis.
I tried to use tight_layout() but it has absolutely no effect.
How can I crop my image correctly such that there is not so much spacing
import numpy as np
import matplotlib.pyplot as plt
# Creating fake data
topn = 15
nb_classes = 13
rows = 27
columns = nb_classes * topn
labels = ['Class {:d}'.format(i) for i in range(nb_classes)]
m = np.random.random((rows,columns))
# Plotting
plt.figure()
plt.imshow(m, interpolation='none')
plt.grid(False)
plt.xlabel('Word', size=16)
plt.ylabel('Dimension', size=16)
ax = plt.gca()
ax.yaxis.set_ticks_position("right")
ax.xaxis.set_ticks_position("top")
yticks = list()
for i in range(0, nb_classes):
if i != 0:
plt.axvline(i*n - 0.5, c='w')
yticks.append((i*n - 0.5 + n/2))
plt.xticks(yticks, labels, rotation=90)
plt.tight_layout()
plt.show()
This is the resulting image (grey lines just to visualize the size):
Use plt.figure(figsize=(8,4)) and aspect='auto' in the call of plt.imshow:
import numpy as np
import matplotlib.pyplot as plt
# Creating fake data
topn = 15
nb_classes = 13
rows = 27
columns = nb_classes * topn
labels = ['Class {:d}'.format(i) for i in range(nb_classes)]
m = np.random.random((rows,columns))
# Plotting
plt.figure(figsize=(8,4))
plt.imshow(m, interpolation='None', aspect='auto')
plt.grid(False)
plt.xlabel('Word', size=16)
plt.ylabel('Dimension', size=16)
ax = plt.gca()
ax.yaxis.set_ticks_position("right")
ax.xaxis.set_ticks_position("top")
yticks = list()
for i in range(0, nb_classes):
if i != 0:
plt.axvline(i*n - 0.5, c='w')
yticks.append((i*n - 0.5 + n/2))
plt.xticks(yticks, labels, rotation=90)
plt.tight_layout()
plt.show()
If you want to insert a small plot inside a bigger one you can use Axes, like here.
The problem is that I don't know how to do the same inside a subplot.
I have several subplots and I would like to plot a small plot inside each subplot.
The example code would be something like this:
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
for i in range(4):
ax = fig.add_subplot(2,2,i)
ax.plot(np.arange(11),np.arange(11),'b')
#b = ax.axes([0.7,0.7,0.2,0.2])
#it gives an error, AxesSubplot is not callable
#b = plt.axes([0.7,0.7,0.2,0.2])
#plt.plot(np.arange(3),np.arange(3)+11,'g')
#it plots the small plot in the selected position of the whole figure, not inside the subplot
Any ideas?
I wrote a function very similar to plt.axes. You could use it for plotting yours sub-subplots. There is an example...
import matplotlib.pyplot as plt
import numpy as np
#def add_subplot_axes(ax,rect,facecolor='w'): # matplotlib 2.0+
def add_subplot_axes(ax,rect,axisbg='w'):
fig = plt.gcf()
box = ax.get_position()
width = box.width
height = box.height
inax_position = ax.transAxes.transform(rect[0:2])
transFigure = fig.transFigure.inverted()
infig_position = transFigure.transform(inax_position)
x = infig_position[0]
y = infig_position[1]
width *= rect[2]
height *= rect[3] # <= Typo was here
#subax = fig.add_axes([x,y,width,height],facecolor=facecolor) # matplotlib 2.0+
subax = fig.add_axes([x,y,width,height],axisbg=axisbg)
x_labelsize = subax.get_xticklabels()[0].get_size()
y_labelsize = subax.get_yticklabels()[0].get_size()
x_labelsize *= rect[2]**0.5
y_labelsize *= rect[3]**0.5
subax.xaxis.set_tick_params(labelsize=x_labelsize)
subax.yaxis.set_tick_params(labelsize=y_labelsize)
return subax
def example1():
fig = plt.figure(figsize=(10,10))
ax = fig.add_subplot(111)
rect = [0.2,0.2,0.7,0.7]
ax1 = add_subplot_axes(ax,rect)
ax2 = add_subplot_axes(ax1,rect)
ax3 = add_subplot_axes(ax2,rect)
plt.show()
def example2():
fig = plt.figure(figsize=(10,10))
axes = []
subpos = [0.2,0.6,0.3,0.3]
x = np.linspace(-np.pi,np.pi)
for i in range(4):
axes.append(fig.add_subplot(2,2,i))
for axis in axes:
axis.set_xlim(-np.pi,np.pi)
axis.set_ylim(-1,3)
axis.plot(x,np.sin(x))
subax1 = add_subplot_axes(axis,subpos)
subax2 = add_subplot_axes(subax1,subpos)
subax1.plot(x,np.sin(x))
subax2.plot(x,np.sin(x))
if __name__ == '__main__':
example2()
plt.show()
You can now do this with matplotlibs inset_axes method (see docs):
from mpl_toolkits.axes_grid.inset_locator import inset_axes
inset_axes = inset_axes(parent_axes,
width="30%", # width = 30% of parent_bbox
height=1., # height : 1 inch
loc=3)
Update: As Kuti pointed out, for matplotlib version 2.1 or above, you should change the import statement to:
from mpl_toolkits.axes_grid1.inset_locator import inset_axes
There is now also a full example showing all different options available.
From matplotlib 3.0 on, you can use matplotlib.axes.Axes.inset_axes:
import numpy as np
import matplotlib.pyplot as plt
fig, axes = plt.subplots(2,2)
for ax in axes.flat:
ax.plot(np.arange(11),np.arange(11))
ins = ax.inset_axes([0.7,0.7,0.2,0.2])
plt.show()
The difference to mpl_toolkits.axes_grid.inset_locator.inset_axes mentionned in #jrieke's answer is that this is a lot easier to use (no extra imports etc.), but has the drawback of being slightly less flexible (no argument for padding or corner locations).
source: https://matplotlib.org/examples/pylab_examples/axes_demo.html
from mpl_toolkits.axes_grid.inset_locator import inset_axes
import matplotlib.pyplot as plt
import numpy as np
# create some data to use for the plot
dt = 0.001
t = np.arange(0.0, 10.0, dt)
r = np.exp(-t[:1000]/0.05) # impulse response
x = np.random.randn(len(t))
s = np.convolve(x, r)[:len(x)]*dt # colored noise
fig = plt.figure(figsize=(9, 4),facecolor='white')
ax = fig.add_subplot(121)
# the main axes is subplot(111) by default
plt.plot(t, s)
plt.axis([0, 1, 1.1*np.amin(s), 2*np.amax(s)])
plt.xlabel('time (s)')
plt.ylabel('current (nA)')
plt.title('Subplot 1: \n Gaussian colored noise')
# this is an inset axes over the main axes
inset_axes = inset_axes(ax,
width="50%", # width = 30% of parent_bbox
height=1.0, # height : 1 inch
loc=1)
n, bins, patches = plt.hist(s, 400, normed=1)
#plt.title('Probability')
plt.xticks([])
plt.yticks([])
ax = fig.add_subplot(122)
# the main axes is subplot(111) by default
plt.plot(t, s)
plt.axis([0, 1, 1.1*np.amin(s), 2*np.amax(s)])
plt.xlabel('time (s)')
plt.ylabel('current (nA)')
plt.title('Subplot 2: \n Gaussian colored noise')
plt.tight_layout()
plt.show()