简体   繁体   中英

How to get x axis title to appear in all subplots of a relplot in Python via Seaborn and Matplotlib?

I cannot get the x axis title to appear for one of my subplots in a relplot. I have three graphs and I did columns and I did col_wrap=2 so I have two graphs on top and one on bottom. The second graph in the first row and the graph in the second row both have x axis titles but the first graph of the first row does not. I got the ticks and their labels to appear with the for loop but not the x axis title.

g = sns.relplot(
    data=data, x="Days", y="Response", col = 'Event', 
col_wrap=2
)

g.set_titles("Events in {col_name}")
g.set_axis_labels("Days", "Response")
for ax in g.axes:
    ax.xaxis.set_tick_params(labelbottom=True)

g.set_axis_labels(...) only sets the outer labels ( docs , almost at the end).

Default, with shared x-axes, only the "outer" xlabels are set visible, the inner ones are set invisible (and seaborn leaves them to be empty strings). So, to see all labels, you need to set both the strings and the visibility explicitly.

At the end, you might want to call plt.tight_layout() to remove the overlapping.

Note that having all the labels repeated over and over, uses screen space without adding real information to the plot.

from matplotlib import pyplot as plt
import seaborn as sns

penguins = sns.load_dataset('penguins')
g = sns.relplot(data=penguins, x='flipper_length_mm', y='body_mass_g', col='species', col_wrap=2,
                height=2, aspect=2)
# g.set_axis_labels("Flipper length", "Body mass")  # only sets the outer labels
for ax in g.axes:
    ax.tick_params(labelbottom=True, labelleft=True)
    ax.set_xlabel("Flipper length", visible=True)
    ax.set_ylabel("Body mass", visible=True)
plt.tight_layout()
plt.show()

带有额外 x 和 y 标签的 sns.relplot

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM