【问题标题】:rotating xticks in seaborn scatterplot [duplicate]在seaborn散点图中旋转xticks [重复]
【发布时间】:2022-10-14 00:37:38
【问题描述】:

我有一个我试图可视化的聚合数据集,它看起来像这样:

我需要为 18 个州绘制一些统计数据。目前情节看起来如下:

我设法使用以下代码设置 xticks,但是没有旋转,我得到一个错误。该图的代码是:

fig, ax = plt.subplots(figsize = (15, 6))
sns.scatterplot(ax = ax, x = 'state', y = 'price per acre, usd', data = data)
ax.set_xlabel("state", size = 12)
ax.set_ylabel('average price per acre of land, usd', size = 12)
ax.set_title('average prices on industrial land', size = 20)
ax.set_xticklabels(data['state'], rotation = 45)
plt.show()

我得到的错误如下所示:

The above exception was the direct cause of the following exception:

KeyError                                  Traceback (most recent call last)
/usr/local/lib/python3.7/dist-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance)
   3361                 return self._engine.get_loc(casted_key)
   3362             except KeyError as err:
-> 3363                 raise KeyError(key) from err
   3364 
   3365         if is_scalar(key) and isna(key) and not self.hasnans:

KeyError: 'state'

那么我如何旋转这些标签(在图中使用状态名称,这样我就不会收到错误并获得视觉上漂亮的图)?带有州名称的列称为“州”,因为它显然来自情节代码

【问题讨论】:

  • ax.set_xticklabels 之前插入的print(data.columns) 的输出是什么?
  • 这是Index(['price', 'square, ac', 'price per acre, usd'], dtype='object')
  • 那么您的state 专栏在哪里?
  • 我不知道,可能它不在这里,因为它是索引,因为这个数据帧是在按状态分组更大的数据帧之后收到的。我现在将编辑问题并插入我要绘制的表格。无论如何,该图确实从 x 轴标签中的某处插入了状态名称
  • state现在是索引,如果你做ax.set_xticklabels(data.index, rotation = 45)呢?

标签: python matplotlib seaborn visualization


【解决方案1】:

如果您想更改刻度参数,例如旋转,使用set_tick_params 而不是随着旋转重新设置标签:

ax.xaxis.set_tick_params(rotation = 45)

【讨论】:

    【解决方案2】:

    感谢stef,我们发现我尝试使用的列的名称实际上是一个索引,所以我修改了该行以在索引中查找那些状态名称并且它起作用了:

    ax.set_xticklabels(data.index, rotation = 45)
    

    【讨论】:

    • 请参阅我的answer 以获得更好的方法。
    猜你喜欢
    • 2021-10-06
    • 2020-08-17
    • 2018-11-09
    • 2020-12-04
    • 2021-10-13
    • 2020-09-28
    • 1970-01-01
    • 2023-01-07
    • 2019-08-04
    相关资源
    最近更新 更多