I start with tree plots:
df = pd.DataFrame([1,20,3],[2,30,4],[3,40,5],columns=['mean','size','stat'])
fig,[ax1,ax2,ax3] = plt.subplots(1, 3, sharey=True)
ax1.barh(np.arange(len(df)),df['mean'].values, align='center')
ax2.barh(np.arange(len(df)),df['size'].values, align='center')
ax3.barh(np.arange(len(df)),df['stat'].values, align='center')
Is there a way to rotate the x axis labels on all three plots?
When you're done plotting, you can just loop over each xticklabel:
for ax in [ax1,ax2,ax3]:
for label in ax.get_xticklabels():
label.set_rotation(90)
You can do it for each ax your are creating:
ax1.xaxis.set_tick_params(rotation=90)
ax2.xaxis.set_tick_params(rotation=90)
ax3.xaxis.set_tick_params(rotation=90)
or you do it inside a for before showing the plot if you are building your axs using subplots:
for s_ax in ax:
s_ax.xaxis.set_tick_params(rotation=90)
df = pd.DataFrame([1,20,3],[2,30,4],[3,40,5],columns=['mean','size','stat'])
fig,[ax1,ax2,ax3] = plt.subplots(1, 3, sharey=True)
plt.subplot(1,3,1)
barh(np.arange(len(df)),df['mean'].values, align='center')
locs, labels = xticks()
xticks(locs, labels, rotation="90")
plt.subplot(1,3,2)
barh(np.arange(len(df)),df['size'].values, align='center')
locs, labels = xticks()
xticks(locs, labels, rotation="90")
plt.subplot(1,3,3)
barh(np.arange(len(df)),df['stat'].values, align='center')
locs, labels = xticks()
xticks(locs, labels, rotation="90")
Should do the trick.
Here is another more generic solution: you can just use axes.flatten() which will provide you with much more flexibility when you have higher dimensions.
for i, ax in enumerate(axes.flatten()):
sns.countplot(x= cats.iloc[:, i], orient='v', ax=ax)
for label in ax.get_xticklabels():
# only rotate one subplot if necessary.
if i==3:
label.set_rotation(90)
fig.tight_layout()
Related
I would like to have an increasing spacing between legend items instead of a single value (labelspacing). The latter only accepts an int value type, but I want a variable spacing between legend items. Also, I want the markerfacecolor to follow the colormap used when creating the scatter plot.
N = 45
x, y = np.random.rand(2, N)
s = np.random.randint(10, 1000, size=N)
fig, ax = plt.subplots()
scatter = ax.scatter(x, y, c=s, s=s)
cbar = fig.colorbar(scatter,
ax=ax,
label='Size',
fraction=0.1,
pad=0.04)
# produce a legend with a cross section of sizes from the scatter
handles, labels = scatter.legend_elements(prop="sizes", alpha=0.6)
for hd in handles:
hd.set_markeredgewidth(2)
hd.set_markeredgecolor("red")
hd.set_markerfacecolor('blue')
legend2 = ax.legend(
handles[::2], labels[::2], loc="upper right", title="Sizes", labelspacing=1.2
)
plt.show()
I searched StackOverflow and tried some possible methods but without success. Could someone guide how I can achieve the desired output?
I managed to set markerfacecolor as the colormap. But I am still struggling with the variable labelspacing!.
Any help!
N = 45
x, y = np.random.rand(2, N)
s = np.random.randint(10, 1000, size=N)
fig, ax = plt.subplots()
scatter = ax.scatter(x, y, c=s, s=s)
cbar = fig.colorbar(scatter,
ax=ax,
label='Size',
fraction=0.1,
pad=0.04)
# produce a legend with a cross section of sizes from the scatter
handles, labels = scatter.legend_elements(prop="sizes", alpha=0.6)
leg_colrs = [color.get_markerfacecolor() for color in scatter.legend_elements()[0]]
for hd, color in zip(handles, leg_colrs):
hd.set_markeredgewidth(2)
hd.set_markeredgecolor("red")
hd.set_markerfacecolor(color)
legend2 = ax.legend(
handles[::2], labels[::2], loc="upper right", title="Sizes", labelspacing=1.2
)
plt.show()
I'm creating subplots. I would like to set the same xtick for all subplots. I was able to set the xlabel in common for all subplots but I really don't know how to do for xticks. Any help?
fig, axs = plt.subplots(2, 2)
axs[0,0].plot(np.float64(datatime),np.float64(Tm),'--',color='black')
axs[0,0].set_ylim([min(Tm)-10,max(Tm)+10])
axs[0,0].set_ylabel('Temp. [°C]')
axs[0,1].plot(np.float64(datatime),np.float64(precip),'--',color='black')
axs[0,1].set_ylim([min(precip),max(precip)+20])
axs[0,1].set_ylabel('Rainfall [mm]')
axs[1,0].plot(np.float64(datatime),np.float64(PET),color='magenta')
axs[1,0].set_ylim([min(PET),max(PET)+10])
axs[1,0].set_ylabel('PET [mm]')
axs[1,1].plot(np.float64(datatime),np.float64(delta),color='cyan')
axs[1,1].set_ylim([min(delta),max(delta)+10])
axs[1,1].set_ylabel('P-PET [mm]')
plt.xticks(np.arange(min(datatime), max(datatime)+1, 12)) #here i define xticks
for ax in axs.flat:
ax.set(xlabel='Time [months]')
plt.show()
Within the for loop you can set the same ticks for each subplot
for ax in axs.flat:
ax.set(xlabel='Time [months]')
ax.set_xticks(np.arange(min(datatime), max(datatime)+1, 12))
I am trying to create two axes within one figure
fig, ax = plt.subplots(2,figsize=(20,16))
This is my first figure:
ax[0].scatter(x,y, color="brown", alpha=0.4, s=200)
ax[0].plot(x,lof, color="brown", alpha=0.4)
for the first axes I want to make the x_ticks and y_ticks bigger how can I go about this?
You can use tick_params:
import matplotlib.pyplot as plt
fig, ax = plt.subplots(2,figsize=(6, 4))
ax[0].scatter([1,2,3],[1,2,3], color="brown", alpha=0.4, s=200)
ax[0].tick_params(width=2, length=4)
ax[1].tick_params(width=3, length=6)
ax[1].plot([1,2,3],[1,2,3], color="brown", alpha=0.4)
With it you can change all appearance properties of it. Here are the docs:
https://matplotlib.org/api/_as_gen/matplotlib.axes.Axes.tick_params.html
One way is to iterate over the major x- and y-ticks of the desired subplot (ax[0] here) and changing their font size.
Minimal representative answer
import matplotlib.pyplot as plt
fig, ax = plt.subplots(2,figsize=(8, 4))
ax[0].scatter([1,2,3],[1,2,3], color="brown", alpha=0.4, s=200)
ax[1].plot([1,2,3],[1,2,3], color="brown", alpha=0.4)
for tick in ax[0].xaxis.get_major_ticks():
tick.label.set_fontsize(16)
for tick in ax[0].yaxis.get_major_ticks():
tick.label.set_fontsize(16)
plt.tight_layout()
plt.show()
If you don't need to differentiate between the X and Y axes, or major and minor ticks, use tick_params:
tick_size = 14
ax.tick_params(size=tick_size)
If you want to change the size of the tick labels, then you want this:
label_size = 14
ax.tick_params(labelsize=label_size)
I can remove the ticks with
ax.set_xticks([])
ax.set_yticks([])
but this removes the labels as well. Any way I can plot the tick labels but not the ticks and the spine
You can set the tick length to 0 using tick_params (http://matplotlib.org/api/axes_api.html#matplotlib.axes.Axes.tick_params):
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot([1],[1])
ax.tick_params(axis=u'both', which=u'both',length=0)
plt.show()
Thanks for your answers #julien-spronck and #cmidi.
As a note, I had to use both methods to make it work:
import numpy as np
import matplotlib.pyplot as plt
fig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(11, 3))
data = np.random.random((4, 4))
ax1.imshow(data)
ax1.set(title='Bad', ylabel='$A_y$')
# plt.setp(ax1.get_xticklabels(), visible=False)
# plt.setp(ax1.get_yticklabels(), visible=False)
ax1.tick_params(axis='both', which='both', length=0)
ax2.imshow(data)
ax2.set(title='Somewhat OK', ylabel='$B_y$')
plt.setp(ax2.get_xticklabels(), visible=False)
plt.setp(ax2.get_yticklabels(), visible=False)
# ax2.tick_params(axis='both', which='both', length=0)
ax3.imshow(data)
ax3.set(title='Nice', ylabel='$C_y$')
plt.setp(ax3.get_xticklabels(), visible=False)
plt.setp(ax3.get_yticklabels(), visible=False)
ax3.tick_params(axis='both', which='both', length=0)
plt.show()
While attending a coursera course on Python, this was a question.
Below is the given solution, which I think is more readable and intuitive.
ax.tick_params(top=False,
bottom=False,
left=False,
right=False,
labelleft=True,
labelbottom=True)
This worked for me:
plt.tick_params(axis='both', labelsize=0, length = 0)
matplotlib.pyplot.setp(*args, **kwargs) is used to set properties of an artist object. You can use this in addition to get_xticklabels() to make it invisible.
something on the lines of the following
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(2,1,1)
ax.set_xlabel("X-Label",fontsize=10,color='red')
plt.setp(ax.get_xticklabels(),visible=False)
Below is the reference page
http://matplotlib.org/api/pyplot_api.html
You can set the yaxis and xaxis set_ticks_position properties so they just show on the left and bottom sides, respectively.
ax.yaxis.set_ticks_position('left')
ax.xaxis.set_ticks_position('bottom')
Furthermore, you can hide the spines as well by setting the set_visible property of the specific spine to False.
axes[i].spines['right'].set_visible(False)
axes[i].spines['top'].set_visible(False)
This Worked out pretty well for me! try it out
import matplotlib.pyplot as plt
import numpy as np
plt.figure()
languages =['Python', 'SQL', 'Java', 'C++', 'JavaScript']
pos = np.arange(len(languages))
popularity = [56, 39, 34, 34, 29]
plt.bar(pos, popularity, align='center')
plt.xticks(pos, languages)
plt.ylabel('% Popularity')
plt.title('Top 5 Languages for Math & Data \nby % popularity on Stack Overflow',
alpha=0.8)
# remove all the ticks (both axes),
plt.tick_params(top='off', bottom='off', left='off', right='off', labelleft='off',
labelbottom='on')
plt.show()
Currently came across the same issue, solved as follows on version 3.3.3:
# My matplotlib ver: 3.3.3
ax.tick_params(tick1On=False) # "for left and bottom ticks"
ax.tick_params(tick2On=False) # "for right and top ticks, which are off by default"
Example:
fig, ax = plt.subplots()
ax.plot([1, 2, 3, 4, 5], [1, 2, 3, 4, 5])
ax.tick_params(tick1On=False)
plt.show()
Output:
Assuming that you want to remove some ticks on the Y axes and only show the yticks that correspond to the ticks that have values higher than 0 you can do the following:
from import matplotlib.pyplot as plt
fig, ax = plt.subplots()
# yticks and yticks labels
yTicks = list(range(26))
yTicks = [yTick if yTick % 5 == 0 else 0 for yTick in yTicks]
yTickLabels = [str(yTick) if yTick % 5 == 0 else '' for yTick in yTicks]
Then you set up your axis object's Y axes as follow:
ax.yaxis.grid(True)
ax.set_yticks(yTicks)
ax.set_yticklabels(yTickLabels, fontsize=6)
fig.savefig('temp.png')
plt.close()
And you'll get a plot like this:
How to change axis weight in matplotlib (make the axis much bolder)?
from pylab import *
x = [5,7,5,9,11,14]
y = [4,5,3,11,15,14]
scatter(x, y, s=50, color='green',marker='h')
show()
You can set the width of whats called a spine (a side of the axes) in Matplotlib:
fig, ax = plt.subplots()
ax.plot(np.random.randn(100).cumsum())
# The spines
plt.setp(ax.spines.values(), linewidth=3)
# The ticks
ax.xaxis.set_tick_params(width=3)
ax.yaxis.set_tick_params(width=3)
Use axhline, axvline:
axhline(linewidth=5, color='black')
axvline(linewidth=5, color='black')
axhline(linewidth=5, y=max(y)*1.1, color='black')
axvline(linewidth=5, x=max(x)*1.1, color='black')