how to show tick labels on top of matplotlib plot? - python

In matplotlib what is the way to have tick labels both at the bottom and in the top x axis? I have searched a lot and still can't find how to do it.

Sorry, I lied in the comments. You can do this easily (but it seems to be badly documented)
fig, ax = plt.subplots(1, 1)
ax.xaxis.set_tick_params(labeltop='on')

You can do it with twiny():
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax2 = ax1.twiny()
X2tick_location= ax1.xaxis.get_ticklocs() #Get the tick locations in data coordinates as a numpy array
ax2.set_xticks(X2tick_location)
ax2.set_xticklabels(X2tick_location)
plt.show()
Have a look to this question too for more elaborate plots.

This seems to be the standard way as of v3.5:
fig, ax = plt.subplots()
ax.tick_params('x', top=True, labeltop=True)
Note that the top keyword draws the ticks and the labeltop keyword draws the labels. Documentation here.

Related

Put shared axis labels to upper plot

from matplotlib import pyplot as plt
fig, (ax0, ax1) = plt.subplots(nrows=2, sharex=True)
fig.show()
Returns this figure:
But I want the x-axis labels below the first plot, not the second, like shown below. How can I achieve this?
There is an example in the official reference, so I answered it by referring to it: In the tick parameter, set the bottom label to false.
import matplotlib.pyplot as plt
ax0 = plt.subplot(211)
ax1 = plt.subplot(212, sharex=ax0, sharey=ax0)
#plt.plot([],[])
plt.tick_params('x', labelbottom=False)
#print(ax1.get_xticks())
plt.show()
The answer from #r-beginners brought me to a solution that also works when using the plt.subplots shortcut instead of instantiating each axis separately.
from matplotlib import pyplot as plt
fig, (ax0, ax1) = plt.subplots(nrows=2, sharex=True)
plt.tick_params('x', labelbottom=False, labeltop=True)
fig.show()
he essential part is plt.tick_params which take keyword arguments labeltop or labelbottom (as well as labelleft or labelright for shared axis on several columns) to select / deselect each axis individually.

Removing legend from mpl parallel coordinates plot?

I have a parallel coordinates plot with lots of data points so I'm trying to use a continuous colour bar to represent that, which I think I have worked out. However, I haven't been able to remove the default key that is put in when creating the plot, which is very long and hinders readability. Is there a way to remove this table to make the graph much easier to read?
This is the code I'm currently using to generate the parallel coordinates plot:
parallel_coordinates(data[[' male_le','
female_le','diet','activity','obese_perc','median_income']],'median_income',colormap = 'rainbow',
alpha = 0.5)
fig, ax = plt.subplots(figsize=(6, 1))
fig.subplots_adjust(bottom=0.5)
cmap = mpl.cm.rainbow
bounds = [0.00,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1.0]
norm = mpl.colors.BoundaryNorm(bounds, cmap.N,)
plt.colorbar(mpl.cm.ScalarMappable(norm = norm, cmap=cmap),cax = ax, orientation = 'horizontal',
label = 'normalised median income', alpha = 0.5)
plt.show()
Current Output:
I want my legend to be represented as a color bar, like this:
Any help would be greatly appreciated. Thanks.
You can use ax.legend_.remove() to remove the legend.
The cax parameter of plt.colorbar indicates the subplot where to put the colorbar. If you leave it out, matplotlib will create a new subplot, "stealing" space from the current subplot (subplots are often referenced to by ax in matplotlib). So, here leaving out cax (adding ax=ax isn't necessary, as here ax is the current subplot) will create the desired colorbar.
The code below uses seaborn's penguin dataset to create a standalone example.
import matplotlib.pyplot as plt
import matplotlib as mpl
import seaborn as sns
import numpy as np
from pandas.plotting import parallel_coordinates
penguins = sns.load_dataset('penguins')
fig, ax = plt.subplots(figsize=(10, 4))
cmap = plt.get_cmap('rainbow')
bounds = np.arange(penguins['body_mass_g'].min(), penguins['body_mass_g'].max() + 200, 200)
norm = mpl.colors.BoundaryNorm(bounds, 256)
penguins = penguins.dropna(subset=['body_mass_g'])
parallel_coordinates(penguins[['bill_length_mm', 'bill_depth_mm', 'flipper_length_mm', 'body_mass_g']],
'body_mass_g', colormap=cmap, alpha=0.5, ax=ax)
ax.legend_.remove()
plt.colorbar(mpl.cm.ScalarMappable(norm=norm, cmap=cmap),
ax=ax, orientation='horizontal', label='body mass', alpha=0.5)
plt.show()

Seaborn heatmaps in subplots - align x-axis

I am trying to plot a figure containing two subplots, a seaborn heatmap and simple matplotlib lines. However, when sharing the x-axis for both plots, they do not align as can be seen in this figure:
It would seem that the problem is similar to this post, but when displaying ax[0].get_xticks() and ax[1].get_xticks() I get the same positions, so I don't know what to change. And in my picture the the deviation seems to be more than a 0.5 shift.
What am I doing wrong?
The code I used to plot the figure is the following:
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
M_1=np.random.random((15,15))
M_2=np.random.random((15,15))
L_1=np.random.random(15)
L_2=np.random.random(15)
x=range(15)
cmap = sns.color_palette("hot", 100)
sns.set(style="white")
fig, ax = plt.subplots(2, 1, sharex='col', figsize=(10, 12))
ax[0].plot(x,L_1,'-', marker='o',color='tab:orange')
sns.heatmap(M_1, cmap=cmap, vmax=np.max(M_1), center=np.max(M_1)/2., square=False, ax=ax[1])
#Mr-T 's comment is spot on. The easiest would be to create the axes beforehand instead of letting heatmap() shrink your axes in order to make room for the colorbar.
There is the added complication that the labels for the heatmap are not actually placed at [0,1,...] but are in the middle of each cell at [0.5, 1.5, ...]. So if you want your upper plot to align with the labels at the bottom (and with the center of each cell), you may have to shift your plot by 0.5 units to the right:
M_1=np.random.random((15,15))
M_2=np.random.random((15,15))
L_1=np.random.random(15)
L_2=np.random.random(15)
x=np.arange(15)
cmap = sns.color_palette("hot", 100)
sns.set(style="white")
fig, ax = plt.subplots(2, 2, sharex='col', gridspec_kw={'width_ratios':[100,5]})
ax[0,1].remove() # remove unused upper right axes
ax[0,0].plot(x+0.5,L_1,'-', marker='o',color='tab:orange')
sns.heatmap(M_1, cmap=cmap, vmax=np.max(M_1), center=np.max(M_1)/2., square=False, ax=ax[1,0], cbar_ax=ax[1,1])

force matplotlib to fix the plot area

I have multiple plots that have the same x-axis. I would like to stack them in a report and have everything line up. However, matplotlib seems to resize them slightly based on the y tick label length.
Is it possible to force the plot area and location to remain the same across plots, relative to the pdf canvas to which I save it?
import numpy as np
import matplotlib.pyplot as plt
xs=np.arange(0.,2.,0.00001)
ys1=np.sin(xs*10.) #makes the long yticklabels
ys2=10.*np.sin(xs*10.)+10. #makes the short yticklabels
fig=plt.figure() #this plot ends up shifted right on the canvas
plt.plot(xs,ys1,linewidth=2.0)
plt.xlabel('x')
plt.ylabel('y')
fig=plt.figure() #this plot ends up further left on the canvas
plt.plot(xs,ys2,linewidth=2.0)
plt.xlabel('x')
plt.ylabel('y')
Your problem is a little unclear, however plotting them as subplots in the same figure should gaurantee that the axes and figure size of the two subplots will be alligned with each other
import numpy as np
import matplotlib.pyplot as plt
xs=np.arange(0.,2.,0.00001)
ys1=np.sin(xs*10.) #makes the long yticklabels
ys2=10.*np.sin(xs*10.)+10. #makes the short yticklabels
fig, (ax1, ax2) = plt.subplots(2, 1)
ax1.plot(xs,ys1,linewidth=2.0)
ax1.set_xlabel('x')
ax1.set_ylabel('y')
ax2.plot(xs,ys2,linewidth=2.0)
ax2.set_xlabel('x')
ax2.set_ylabel('y')
plt.subplots_adjust(hspace=0.3) # adjust spacing between plots
plt.show()
This produces the following figure:
I had the same problem. The following works for me.
Force the same figure width for all your plots around all your python scripts, for example:
fig1 = plt.figure(figsize=(12,6))
...
fig2 = plt.figure(figsize=(12,4))
And do not use (very important!):
fig.tight_layout()
Save the figure
plt.savefig('figure.png')
Plot areas should now be the same.
using subplots with the same x-axis should do the trick.
use sharex=True when you create the subplots. The benefit of sharex is that zooming or panning on 1 subplot will also auto-update on all subplots with shared axes.
import numpy as np
import matplotlib.pyplot as plt
xs = np.arange(0., 2., 0.00001)
ys1 = np.sin(xs * 10.) # makes the long yticklabels
ys2 = 10. * np.sin(xs * 10.) + 10. # makes the short yticklabels
fig, (ax1, ax2) = plt.subplots(2, sharex=True)
ax1.plot(xs, ys1, linewidth=2.0)
ax1.xlabel('x')
ax1.ylabel('y')
ax2.plot(xs, ys2, linewidth=2.0)
ax2.xlabel('x')
ax2.ylabel('y')
plt.show()

matplotlib share x axis but don't show x axis tick labels for both, just one

I'm using python + matplotlib and I'm having two plots share an axis. If you try to set graph1.set_xticklabels([]) while sharing an axis, it has no effect because it is shared. Is there a way to share the axis AND be able to hide the x axis of one plot?
This is a common gotcha when using shared axes.
Fortunately, there's a simple fix: use plt.setp(ax.get_xticklabels(), visible=False) to make the labels invisible on just one axis.
This is equivalent to [label.set_visible(False) for label in ax.get_xticklabels()], for whatever it's worth. setp will automatically operate on an iterable of matplotlib objects, as well as individual objects.
As an example:
import matplotlib.pyplot as plt
fig = plt.figure()
ax1 = fig.add_subplot(2,1,1)
ax1.plot(range(10), 'b-')
ax2 = fig.add_subplot(2,1,2, sharex=ax1)
ax2.plot(range(10), 'r-')
plt.setp(ax1.get_xticklabels(), visible=False)
plt.show()
Per a thread on matplotlib-users, you could use
import matplotlib.pyplot as plt
for ax in plt.gcf().axes:
try:
ax.label_outer()
except:
pass
You could use Axes.tick_params():
import matplotlib.pyplot as plt
fig = plt.figure()
ax1 = fig.add_subplot(211)
ax2 = fig.add_subplot(212, sharex=ax1)
ax1.tick_params(labelbottom=False)
You can share the axes during subplot creation with plt.subplots as
fig, axes = plt.subplots(nrows=2, sharex=True)
This will automatically turn the ticklabels for inner axes off.
Complete example:
import matplotlib.pyplot as plt
fig, axes = plt.subplots(nrows=2, sharex=True)
axes[0].plot([1,2,3])
axes[1].plot([3,2,1])
plt.show()
Unfortunately, I am not allowed to comment on esmit's answer (which is the best solution in my opinion, thanks esmit), so I have to write my comment as a new answer: I put his solution into a simple function
def remove_inner_ticklabels(fig):
for ax in fig.axes:
try:
ax.label_outer()
except:
pass
which you can call before plt.show(). Joe Kington's answer did not work for me for some reason.

Categories

Resources