【问题标题】:Rotating all the axis' in a seaborn subplots在 seaborn 子图中旋转所有轴
【发布时间】:2021-09-20 12:26:45
【问题描述】:

我正在尝试使用带有旋转轴的 seaborn facetgrid 子图,但我似乎无法旋转所有轴,只能旋转最后一个轴。有小费吗?下面的代码使图表只剩下最后一个带有旋转轴的子图。

# Create a grid : initialize it
g = sns.FacetGrid(df_full_year, col='segment', hue='segment', col_wrap=4,sharey=False,sharex=False)

# Add the line over the area with the plot function
g = g.map(plt.bar, 'Currency', 'received_usd')
 
# Fill the area with fill_between
g = g.map(plt.bar, 'Currency', 'received_usd', alpha=.6).set_titles("{col_name} country")
 
# Control the title of each facet
g = g.set_titles("{col_name}")
 
# Add a title for the whole plot
plt.subplots_adjust(top=.92)
g = g.fig.suptitle('Evolution of the value of stuff in 16 countries')

plt.xticks(rotation=45)

# Show the graph
plt.show()

【问题讨论】:

  • 请不要不断地将g分配给其他函数的结果。只需从g = sns.FacetGrid(...) 开始,别管它。您可以使用g.set_xticklabels(rotation=45),参见例如How to rotate xticklabels in a seaborn catplot
  • 谢谢,但事实并非如此。上面的代码仅旋转 facetgrid 中最后一个图表上的轴。我可以使用 catplot,但只是想知道为什么它只旋转最后一张图表上的数据。
  • 假设您使用的是最新的 seaborn 和 matplotlib 版本,g.set_xticklabels(rotation=45) 会旋转所有子图的所有可见刻度标签。但是您确实需要从g = g.fig.suptitle(...) 中删除g = ,因为g.fig.suptitle() 的结果不再是FacetGrid。关于catplot 的链接帖子并不意味着您需要使用catplotcatplot 只是另一个返回FacetGrid 的函数,可以以相同的方式设置标签旋转。

标签: python seaborn facet-grid


【解决方案1】:

x 刻度标签可以用g.set_xticklabels(rotation=45) 旋转。 代码中的错误是赋值g = g.fig.suptitle(...),因为g.fig.suptitle(...) 返回的是字幕的文本元素,而不是FacetGridg 的所有其他分配,除了第一个,都应该被删除,因为它们没有用并引入潜在的错误。请注意,g.fig.tight_layout() 将调整空白,因此一切都很好。

这是一些示例代码,从虚拟测试数据开始:

import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np

df_full_year = pd.DataFrame({'segment': np.repeat(np.arange(1, 9), 10),
                             'Currency': np.tile([*'abcdefghij'], 8),
                             'received_usd': np.random.randint(20, 50, 80)})

g = sns.FacetGrid(df_full_year, col='segment', hue='segment', col_wrap=4, sharey=False, sharex=False)

g.map(plt.bar, 'Currency', 'received_usd')
g.set_titles("{col_name} country")
g.fig.suptitle('Evolution of the value of stuff in 16 countries')

g.set_xticklabels(rotation=45)

g.fig.tight_layout()
plt.show()

【讨论】:

    猜你喜欢
    • 2020-05-07
    • 2019-08-25
    • 1970-01-01
    • 2019-02-10
    • 1970-01-01
    • 2021-01-01
    • 1970-01-01
    • 2020-08-26
    相关资源
    最近更新 更多