【发布时间】: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