【问题标题】:How to plot observations from each row of a dataframe as a line plot如何将数据框每一行的观察结果绘制为线图
【发布时间】:2021-10-17 02:28:05
【问题描述】:

我想在一张图表中显示多个数据集。

但我似乎无法让 y 轴工作并得到以下错误:ValueError: x and y must have same first dimension, but have shapes (2,) and (6060000,)

由于我还是一个初学者,并且我从不同的来源复制了部分代码,我的代码很可能在某些地方很糟糕。

我从未问过任何 pandas/matplotlib 问题,所以我希望这是可重现的。

数据框有很多列,但代码示例中只提供了一小部分。

import datetime as dt
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import pandas as pd

channel_data = pd.DataFrame({'Creation date': ['2014-01-02', '2013-09-11', '2007-08-19'], 'Subscriber count': [6060000, 4110000, 4440000    ]})

# get x and y from first channel
now = str(dt.datetime.now())
now = now[:10]

dates = [channel_data["Creation date"][0], now]
dates2 = [channel_data["Creation date"][1], now]
dates3 = [channel_data["Creation date"][2], now]
x1 = [dt.datetime.strptime(d,'%Y-%m-%d').date() for d in dates]
x2 = [dt.datetime.strptime(d,'%Y-%m-%d').date() for d in dates2]
x3 = [dt.datetime.strptime(d,'%Y-%m-%d').date() for d in dates3]

# PROBLEM HERE

y1 = range(len(x1)) # i got the x axis to work but am having problems with this part
y2 = range(len(x2))
y3 = range(len(x3))

#y1 = range(0, channel_data["Subscriber count"][0])
# this was my idea of displaying the data (y-axis)
# -----------------------------------------------------------

plt.figure(figsize=(10, 5))
plt.title("Channel growth over time [USD]", fontdict={"fontweight": "bold"})


plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%Y'))

plt.plot(x1, y1, "b.-", label="Carwow") #b.- to choose color=blue, pointer=. , line=normal line 
plt.plot(x2, y2, "r.-", label="Doug Demuro")
plt.plot(x3, y3, "g.-", label="Scotty Kilmer")

plt.xlabel("Date", fontdict={"fontsize": 13})
plt.ylabel("Subscribers", fontdict={"fontsize": 12})

plt.legend()

plt.show()

第一张图片显示了当前图表(y 值错误)。 第二张图片显示了我想要如何显示数据的示意图。

我知道这一次有很多问题要问,但也许只是有一个想法或一个我可以去的方向。尝试了很多东西,但没有任何效果。

感谢您的阅读。

【问题讨论】:

    标签: python pandas matplotlib plot


    【解决方案1】:
    • 请注意,这不是可视化增长率的正确方法。该图意味着线性增长,因为您只是在两点之间绘制一条线。增长率应根据其他日期的中间计数确定。
    • 错误发生在plt.plot(x1, y1,...),因为x1 的长度是d in dates(即2),但y1 的长度是6060000。
    • 使用pandas.DataFrame.iterrows 迭代并绘制每个观察值。
    • xy 的每个 list 由 2 个值组成
      • x 总是从创建日期开始,到 now 结束
      • y 总是从 0 开始,到订阅者计数结束
    import pandas as pd
    import matplotlib.pyplot as plt
    
    # crate a dataframe
    df = pd.DataFrame({'Creation date': ['2014-01-02', '2013-09-11', '2007-08-19'], 'Subscriber count': [6060000, 4110000, 4440000], 'Channel name': ['Carwow', 'Doug Demuro', 'Scotty Kilmer']})
    
    # convert any date columns to a datetime dtype
    df['Creation date'] = pd.to_datetime(df['Creation date']).dt.date
    
    # display(df)
      Creation date  Subscriber count   Channel name
    0    2014-01-02           6060000         Carwow
    1    2013-09-11           4110000    Doug Demuro
    2    2007-08-19           4440000  Scotty Kilmer
    
    # get the current datetime date
    now = datetime.now().date()
    
    # iterate through the rows and plot
    for i, v in df.iterrows():
        
        # get the values and labels to plot
        x0 = v['Creation date']
        y1 = v['Subscriber count']
        label = v['Channel name']
    
        plt.plot([x0, now], [0, y1], label=label)
        
    plt.legend()
    

    【讨论】:

    • 嗨特伦顿。非常感谢您的反馈和帮助。我知道这不是显示增长率的好方法,但我只是在试验我拥有的数据(遗憾的是只有 2 个值)。我现在也让它工作了。真棒
    • @CallTheDay 很高兴这解决了您的直接问题。
    猜你喜欢
    • 1970-01-01
    • 2020-05-02
    • 1970-01-01
    • 2020-03-27
    • 1970-01-01
    • 1970-01-01
    • 2013-07-12
    • 2018-03-14
    • 1970-01-01
    相关资源
    最近更新 更多