Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a shared x-label and y-label to a plot created with pandas' plot?

One can create subplots easily from a dataframe using pandas:

import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame({'A': [0.3, 0.2, 0.5, 0.2], 'B': [0.1, 0.0, 0.3, 0.1], 'C': [0.2, 0.5, 0.0, 0.7], 'D': [0.6, 0.3, 0.4, 0.6]}, index=list('abcd'))

ax = df.plot(kind="bar", subplots=True, layout=(2, 2), sharey=True, sharex=True, rot=0, fontsize=20)

How would one now add the x- and y-labels to the resulting plot? Here it is explained for a single plot. So if I wanted to add labels to a particular subplot I could do:

ax[1][0].set_xlabel('my_general_xlabel')
ax[0][0].set_ylabel('my_general_ylabel')
plt.show()

That gives:

enter image description here

How would one add the labels so that they are centred and do not just refer to a one row/column?

like image 534
Cleb Avatar asked Feb 21 '17 16:02

Cleb


People also ask

How to set xlabel and ylabel in a plot in pandas?

In Pandas version 1.10 you can use parameters xlabel and ylabel in the method plot: The df.plot () function returns a matplotlib.axes.AxesSubplot object. You can set the labels on that object. Or, more succinctly: ax.set (xlabel="x label", ylabel="y label").

How to create labels for a plot in Pyplot?

Creating Labels for a Plot. By using pyplot () function of library we can add xlabel () and ylabel () to set x and y labels. Example: Let’s add Label in the above Plot.

How to set labels on a DF2 plot?

The df.plot()function returns a matplotlib.axes.AxesSubplotobject. You can set the labels on that object. ax = df2.plot(lw=2, colormap='jet', marker='.', markersize=10, title='Video streaming dropout by category') ax.set_xlabel("x label") ax.set_ylabel("y label")

How to add labels to the x-axis of a graph?

You can set the labels on that object. Or, more succinctly: ax.set (xlabel="x label", ylabel="y label"). Alternatively, the index x-axis label is automatically set to the Index name, if it has one. so df2.index.name = 'x label' would work too.


2 Answers

X and y labels are bound to an axes in matplotlib. So it makes little sense to use xlabel or ylabel commands for the purpose of labeling several subplots.

What is possible though, is to create a simple text and place it at the desired position. fig.text(x,y, text) places some text at coordinates x and y in figure coordinates, i.e. the lower left corner of the figure has coordinates (0,0) the upper right one (1,1).

import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame({'A': [0.3, 0.2, 0.5, 0.2], 'B': [0.1, 0.0, 0.3, 0.1], 'C': [0.2, 0.5, 0.0, 0.7], 'D': [0.6, 0.3, 0.4, 0.6]}, index=list('abcd'))
axes = df.plot(kind="bar", subplots=True, layout=(2,2), sharey=True, sharex=True)

fig=axes[0,0].figure
fig.text(0.5,0.04, "Some very long and even longer xlabel", ha="center", va="center")
fig.text(0.05,0.5, "Some quite extensive ylabel", ha="center", va="center", rotation=90)

plt.show()

enter image description here

The drawback of this solution is that the coordinates of where to place the text need to be set manually and may depend on the figure size.

like image 162
ImportanceOfBeingErnest Avatar answered Oct 18 '22 12:10

ImportanceOfBeingErnest


Another solution: create a big subplot and then set the common labels. Here is what I got.

enter image description here

The source code is below.

import pandas as pd
import matplotlib.pyplot as plt

fig = plt.figure()
axarr = fig.add_subplot(221)   

df = pd.DataFrame({'A': [0.3, 0.2, 0.5, 0.2], 'B': [0.1, 0.0, 0.3, 0.1], 'C': [0.2, 0.5, 0.0, 0.7], 'D': [0.6, 0.3, 0.4, 0.6]}, index=list('abcd'))
axes = df.plot(kind="bar", ax=axarr, subplots=True, layout=(2, 2), sharey=True, sharex=True, rot=0, fontsize=20)

# Create a big subplot
ax = fig.add_subplot(111, frameon=False)
# hide tick and tick label of the big axes
plt.tick_params(labelcolor='none', top='off', bottom='off', left='off', right='off')

ax.set_xlabel('my_general_xlabel', labelpad=10) # Use argument `labelpad` to move label downwards.
ax.set_ylabel('my_general_ylabel', labelpad=20)

plt.show()
like image 39
SparkAndShine Avatar answered Oct 18 '22 11:10

SparkAndShine