【问题标题】:Plot three different columns on y axis using python使用python在y轴上绘制三个不同的列
【发布时间】:2021-03-03 05:08:45
【问题描述】:

我正在尝试用每列一条线绘制线图。我的数据集如下所示:

我正在使用此代码,但它给了我以下错误: ValueError: 传递的项目数错误 3,位置暗示 27

plot_x = 'bill__effective_due_date'
plot_y = ['RR_bucket1_perc', 'RR_bucket7_perc', 'RR_bucket14_perc']

ax = sns.pointplot(x=plot_x, y=plot_y, data=df_rollrates_plot, marker="o", palette=sns.color_palette("coolwarm"))

display(ax.figure)

也许这是一个愚蠢的问题,但我是 python 新手,所以我不知道该怎么做。这是我的预期输出:

谢谢!!

【问题讨论】:

  • 你好像在找sns.lineplot()
  • 如果你不介意不使用 seaborn,在 Pandas 中很简单:df_rollrates_plot.plot(x = plot_x, y = plot_y)。另外,请确保您已将日期解析为日期(阅读表格时,请使用read_csv 中的parse_dates="bill__effective_due_date" 选项。

标签: python seaborn line-plot


【解决方案1】:

您的数据形状错误,无法利用 seaborn 线图中的 hue 参数。您需要将其堆叠,以便列成为分类值。

import pandas as pd
import seaborn as sns
rr1 = [20,10,2,10,2,5]
rr7 = [17,8,2,8,2,4]
rr14 = [12,5,2,5,2,3]
x = ['Nov-1','Nov2','Nov-3','Nov-4','Nov-5','Nov-6']

df = pd.DataFrame({'bill_effective_due_date':x,
                                  'RR_bucket1_perc':rr1, 
                                  'RR_bucket7_perc':rr7, 
                                  'RR_bucket14_perc':rr14})

# This is where you are reshaping your data to make it work like you want
df = df.set_index('bill_effective_due_date').stack().reset_index()
df.columns=['bill_effective_due_date','roll_rates_perc','roll_rates']

sns.lineplot(data=df, x='bill_effective_due_date',y='roll_rates', hue='roll_rates_perc', marker='o')

【讨论】:

    【解决方案2】:

    您可以按如下方式绘制数据框(编辑:我更新了下面的代码以使 bill__effective_due_date 成为数据框的索引):

    import seaborn as sns
    import pandas as pd
    
    rr1 = [20,10,2,10,2,5]
    rr7 = [17,8,2,8,2,4]
    rr14 = [12,5,2,5,2,3]
    x = ['Nov-1','Nov2','Nov-3','Nov-4','Nov-5','Nov-6']
    
    df_rollrates_plot = pd.DataFrame({'RR_bucket1_perc':rr1, 
                                      'RR_bucket7_perc':rr7, 
                                      'RR_bucket14_perc':rr14})
    
    df_rollrates_plot.index = x
    df_rollrates_plot.index.name = 'bill__effective_due_date'
    
    sns.lineplot(data=df_rollrates_plot)
    plt.grid()
    

    【讨论】:

      猜你喜欢
      • 2020-10-09
      • 1970-01-01
      • 2015-04-04
      • 2013-04-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-30
      • 1970-01-01
      相关资源
      最近更新 更多