python - 如何使用 seaborn.relplot 绘制宽格式数据框
问题描述
我正在尝试使用 5 个城市(C1-C5)的虚拟数据绘制以下折线图。
根据我的理解x="Year"
,y="Number of Employees"
和hue="City"
。我将如何设置它的代码?我尝试过以下方式,但它不起作用!
当前代码
import seaborn as sns
import pandas as pd
Areas = r'C:\Users\Tachi\Desktop\City.xlsx'
df = pd.read_excel(Areas)
df.set_index('City', inplace=True)
sns.relplot(x="Year", y="Number of Employees",hue="City", kind="line", data=df)
样本数据
data = {'City': ['C1', 'C2', 'C3', 'C4', 'C5'],
2015: [28564, 2585, 4679, 33227, 2000],
2016: [83659, 4429, 35834, 1447, 3454],
2017: [0, 453, 40903, 46826, 646],
2018: [39470, 8364, 29464, 36443, 8364]}
df = pd.DataFrame(data)
df.set_index('City', inplace=True)
2015 2016 2017 2018
City
C1 28564 83659 0 39470
C2 2585 4429 453 8364
C3 4679 35834 40903 29464
C4 33227 1447 46826 36443
C5 2000 3454 646 8364
解决方案
- 给定 OP 中的测试数据框 ,
df
绘制数据框的最简单方法是使用pandas.DataFrame.transpose
, 并seaborn.relplot
使用宽格式绘制。- 这会自动将数据框索引用作 x 轴,并将列标题用作
hue
. - 也可以使用
sns.lineplot(data=df, marker='o')
而不是使用来生成可视化relplot
。
- 这会自动将数据框索引用作 x 轴,并将列标题用作
# transpose the dataframe
df = df.T
# display(df)
City C1 C2 C3 C4 C5
2015 28564 2585 4679 33227 2000
2016 83659 4429 35834 1447 3454
2017 0 453 40903 46826 646
2018 39470 8364 29464 36443 8364
# plot the dataframe
sns.relplot(data=df, kind='line', marker='o')
- 索引值为
int dtype
,因此 x 轴使用中间数字格式化。str dtype
解决此问题的一种方法是在绘图之前将索引转换为 a 。
# set the index of years to a str dtype
df.index = df.index.astype(str)
# plot the dataframe
sns.relplot(data=df, kind='line', marker='o')
推荐阅读
- selenium - Selenium 无效参数
- java - Android Studio 解析 JSON 对象不起作用
- c++ - 使用 realloc 增加大小与创建更大的动态数组
- r - 来自导入包的“已覆盖注册的 S3 方法”消息
- api-gateway - 如何在微服务中实现 API 网关
- android-studio - 已指定命名参数“child”的参数
- face-recognition - 如何防止这种人脸识别错误?
- javascript - 如何在 React Native 应用程序中创建和管理 icalendar VEvent
- reactjs - 尝试访问公开可用的端点时,部署到 firebase 的 React-app 出现 cors 错误
- amp-html - AMP 表单 - 输入 [值] 不允许使用 concat() 函数