繁体   English   中英

如何 plot 宽格式 dataframe 与 seaborn.relplot

[英]How to plot wide format dataframe with seaborn.relplot

我正在尝试 plot 以下折线图,其中包含 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
  • Given the test dataframe, df , in the OP, the easiest way to plot the dataframe is to use pandas.DataFrame.transpose , and plot with seaborn.relplot using a wide format .
    • 这会自动使用 dataframe 索引作为 x 轴,并使用hue的列标题。
    • 也可以使用sns.lineplot(data=df, marker='o')而不是使用relplot化。
# 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
# 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')

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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