This question already has answers here:
Show tick labels when sharing an axis in matplotlib
(3 answers)
Closed 4 years ago.
When use sharex or sharey in subplots, the tick labels would disappeared, how to turn them back?
Here is an example just copied from the official website:
fig, axs = plt.subplots(2, 2, sharex=True, sharey=True)
axs[0, 0].plot(x)
plt.show()
And we will see:
As we can see, the top-right plot doesn't have any tick labels, and others also lack some labels because of the axis was shared.
I think I should use something like plt.setp(ax.get_xticklabels(), visible=True), but it doesn't work.
You can use the tick_params() to design the plot:
f, ax = plt.subplots(2, 2, sharex=True, sharey=True)
for a in f.axes:
a.tick_params(
axis='x', # changes apply to the x-axis
which='both', # both major and minor ticks are affected
bottom=True,
top=False,
labelbottom=True) # labels along the bottom edge are on
plt.show()
Related
This question already has answers here:
How do I change the size of figures drawn with Matplotlib?
(14 answers)
Closed 8 months ago.
I plotted some graphs with subplot by the code bellow :
fig, axs = plt.subplots(1, 2)
for i in range (len(Yallp)):
axs[0].plot(Dt,Yall[i])
axs[1].plot(Dt,Yallp[i])
for ax in axs.flat:
ax.set(xlabel='time scales', ylabel='$<C_{ij}>_{ij}$')
for ax in axs.flat:
ax.label_outer()
axs[0].grid()
axs[1].grid()
'Yall' and 'Yallp' are two arrays of the same shape.
I want to plot these arrays but I don't know how I can choose the size of the graphics. With subplot, python draws me graphs with a standard size and I want to enlarge them.
You can change the size of your plots with figsize parameter:
fig, axs = plt.subplots(1, 2, figsize=(8,6))
I have been using this piece of code for drawing 2 subplots on the same figure. I tried many things for adding space between bars of barh in matplotlib so the labels of y-axis would be readable but I could not fix it:
plt.figure(figsize=(30, 120))
fig, axes = plt.subplots(ncols=2, sharey=True)
axes[0].barh(names, gaps, align='edge', color='green',height=1)
axes[1].barh(names, mems, align='edge', color='blue',height=1)
axes[0].invert_xaxis()
axes[0].set_yticklabels(names, fontsize=5)
axes[0].yaxis.tick_right()
for ax in axes.flat:
ax.margins(0.01)
ax.grid(True)
fig.tight_layout()
fig.subplots_adjust(wspace=0.37)
My current figure looks like this:
my current figure
Do you know how I can make the ylabels readable?
I have been playing a bit with plt.legend() and ax.legend() and legend from seaborn itself and I think I'm missing something.
My first question is, could someone please explain to me how those go together, how they work and if I have subplots, what is superior to what? Meaning can I set a general definition (eg. have this legend in all subplots in this loc) and then overwrite this definition for specific subplots (eg by ax.legend())?
My second question is practical and showing my problems. Let's take the seaborn Smokers data set to illustrate it on:
import seaborn as sns
import matplotlib.pyplot as plt
tips = sns.load_dataset("tips")
# define sizes for labels, ticks, text, ...
# as defined here https://stackoverflow.com/questions/3899980/how-to-change-the-font-size-on-a-matplotlib-plot
SMALL_SIZE = 10
MEDIUM_SIZE = 14
BIGGER_SIZE = 18
plt.rc('font', size=SMALL_SIZE) # controls default text sizes
plt.rc('axes', titlesize=SMALL_SIZE) # fontsize of the axes title
plt.rc('axes', labelsize=BIGGER_SIZE) # fontsize of the x and y labels
plt.rc('xtick', labelsize=MEDIUM_SIZE) # fontsize of the tick labels
plt.rc('ytick', labelsize=MEDIUM_SIZE) # fontsize of the tick labels
plt.rc('legend', fontsize=SMALL_SIZE) # legend fontsize
plt.rc('figure', titlesize=BIGGER_SIZE) # fontsize of the figure title
# create figure
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(nrows=2, ncols=2, figsize=(16,12))
ylim = (0,1)
sns.boxplot(x= 'day', y= 'tip', hue="sex",
data=tips, palette="Set2", ax=ax1)
sns.swarmplot(x= 'day', y= 'tip', hue="sex",
data=tips, palette="Set2", ax=ax2)
ax2.legend(loc='upper right')
sns.boxplot(x= 'day', y= 'total_bill', hue="sex",
data=tips, palette="Set2", ax=ax3)
sns.swarmplot(x= 'day', y= 'total_bill', hue="sex",
data=tips, palette="Set2", ax=ax4)
plt.suptitle('Smokers')
plt.legend(loc='upper right')
plt.savefig('test.png', dpi = 150)
If I use simply seaborn, I get a legend as in Subplot 1 and 3 -- it has the 'hue' label and follows defined font size. However, I'm not able to control its location (it has some default, see the difference between 1 and 3). If I use ax.legend() as in Subplot 2, then I can modify specific subplot but I lose the seaborn 'hue' feature (notice that the "sex" disappears) and it does not follow my font definitions. If I use plt.legend(), it only affects the Subplot before it (Subplot 4 in this case).
How can I unite all this? Eg. to have one definition for all subplots or how to control the seaborn default? To make clear goal, how to have a legend as in Subplot 1 where the labels come automatically from the data (but I can change them) and the location, font size, ... is set the same for all the subplots (eg. upper right, font size of 10, ...)?
Thank you for help and explanation.
Seaborn legends are always called with the keyword loc=best. This is hardcoded in the sourcecode. You could change the sourcecode, e.g. in this line and replace by ax.legend(). Then setting the rc parameter in your code like
plt.rc('legend', loc="upper right")
would give the desired output.
The only other option is to create the legend manually, like you do in the second case,
ax2.legend(loc="upper right", title="sex", title_fontsize="x-large")
This question already has answers here:
matplotlib - No xlabel and xticks for twinx axes in subploted figures
(2 answers)
Closed 5 years ago.
This happens when I try to plot a line and an area on the same subplot. I found the my x-ticks disappear after I call ay=ax.twinx() and plot on ay.
Here's my code that causes this error.
fig, axes = plt.subplots(nrows=2, ncols=1, figsize=[12,12])
data=pd.DataFrame([[1,2,3],[2,3,4],[3,2,4]])
ix = np.unravel_index(0, axes.shape)
ax=axes[ix]
y=pd.DataFrame(data.iloc[:,0]-data.iloc[:,1])
ax2=ax.twinx()
data.plot(ax=ax,color=['navy','red'])
ax2.plot(y.values, linewidth=2.0)
As you can see, the x-ticks disappear.
However, if you continue plotting, you can find the last subplot isn't affected.
fig, axes = plt.subplots(nrows=2, ncols=1, figsize=[12,12])
data=pd.DataFrame([[1,2,3],[2,3,4],[3,2,4]])
ix = np.unravel_index(0, axes.shape)
ax=axes[ix]
y=pd.DataFrame(data.iloc[:,0]-data.iloc[:,1])
ax2=ax.twinx()
data.plot(ax=ax,color=['navy','red'])
ax2.plot(y.values, linewidth=2.0)
ix = np.unravel_index(1, axes.shape)
ax=axes[ix]
y=pd.DataFrame(data.iloc[:,0]-data.iloc[:,1])
ax2=ax.twinx()
data.plot(ax=ax,color=['navy','red'])
ax2.plot(y.values, linewidth=2.0)
There are two options. One is based on the answer to this question: matplotlib - pandas - No xlabel and xticks for twinx axes in subploted figures
which is to reverse the order of plotting. First plot to the two subplots, then create the twin axes for both.
import matplotlib.pyplot as plt
import pandas as pd
fig, axes = plt.subplots(nrows=2, ncols=1)
data=pd.DataFrame([[1,2,3],[2,3,4],[3,2,4]])
ax=axes[0]
y=pd.DataFrame(data.iloc[:,0]-data.iloc[:,1])
data.plot(ax=ax)
ax3=axes[1]
y=pd.DataFrame(data.iloc[:,0]-data.iloc[:,1])
data.plot(ax=ax3)
ax2=ax.twinx()
ax2.plot(y.values)
ax4=ax3.twinx()
ax4.plot(y.values)
plt.show()
Now sometimes the above may not be an option, so the second possible solution would be to set the ticks visible again after the complete plot has been generated.
[t.set_visible(True) for t in ax.get_xticklabels()]
Complete example:
import matplotlib.pyplot as plt
import pandas as pd
fig, axes = plt.subplots(nrows=2, ncols=1)
data=pd.DataFrame([[1,2,3],[2,3,4],[3,2,4]])
ax=axes[0]
y=pd.DataFrame(data.iloc[:,0]-data.iloc[:,1])
ax2=ax.twinx()
data.plot(ax=ax)
ax2.plot(y.values)
ax3=axes[1]
y=pd.DataFrame(data.iloc[:,0]-data.iloc[:,1])
ax4=ax3.twinx()
data.plot(ax=ax3)
ax4.plot(y.values)
[t.set_visible(True) for t in ax.get_xticklabels()]
plt.show()
This question already has answers here:
Remove xticks in a matplotlib plot?
(11 answers)
Closed 8 years ago.
I'm using subplots in matplotlib. Since all of my subplots have the same x-axis, I only want to label the x-axis on my bottom plot. How can I remove xtics from just one axis?
As pointed out here, the following works!
plt.tick_params(\
axis='x', # changes apply to the x-axis
which='both', # both major and minor ticks are affected
bottom='off', # ticks along the bottom edge are off
top='off', # ticks along the top edge are off
labelbottom='off') # labels along the bottom edge are off
Dan, if you've set up your plots in an OOP way using
import matplotlib.pyplot as plt
fig, ax_arr = subplots(3, 1, sharex=True)
then it should be easy to hide the x-axis labels using something like
plt.setp([a.get_xticklabels() for a in f.axes[:-1]], visible=False)
# or
plt.setp([a.get_xticklabels() for a in ax_arr[:-1]], visible=False)
But check out this link and some of the further down examples will prove useful.
Edit:
If you can't use plt.subplots(), I'm still assuming you can do
import matplotlib.pyplot as plt
fig = plt.figure()
ax1 = fig.add_subplot(211)
ax2 = fig.add_subplot(212)
ax1.plot(x1, y1)
ax2.plot(x2, y2)
plt.setp(ax1.get_xticklabels(), visible=False)
If you have more than 2 subplots, such as
ax1 = fig.add_subplot(N11)
ax2 = fig.add_subplot(N12)
...
axN = fig.add_subplot(N1N)
plt.setp([a.get_xticklabels() for a in (ax1, ..., axN-1)], visible=False)