【问题标题】:How do I categorise and plot data from a Pandas dataframe using Matplotlib?如何使用 Matplotlib 对 Pandas 数据框中的数据进行分类和绘制?
【发布时间】:2019-08-14 09:29:27
【问题描述】:

我有一个 DataFrame 的推文值,并想绘制 'Favourites''Date' 的图表,并按 'User' 对数据进行分类/颜色编码。

我能够获得数据的散点图或条形图,但无法获得基于 'User' 进行分类的有效解决方案。 'Date' 在图表中也很乱,我无法理解这个问题的原因。

我尝试使用this tutorial 获取折线图,但不明白如何将其应用于我的DataFrame

数据帧结构

data_frame = pandas.DataFrame(data=[tweet.text for tweet in tweets], columns=['Tweets'])

data_frame['User'] = numpy.array([tweet.user.screen_name for tweet in tweets])
data_frame['ID'] = numpy.array([tweet.id for tweet in tweets])
data_frame['Length'] = numpy.array([len(tweet.text) for tweet in tweets])
data_frame['Date'] = numpy.array([tweet.created_at for tweet in tweets])
data_frame['Source'] = numpy.array([tweet.source for tweet in tweets])
data_frame['Favourites'] = numpy.array([tweet.favorite_count for tweet in tweets])
data_frame['Retweets'] = numpy.array([tweet.retweet_count for tweet in tweets])

return data_frame

绘图

x = result.Date
y = result.Favourites

plt.xlabel("Date", fontsize=10)
plt.ylabel("Favourites", fontsize=10)


plt.figure(figsize=(30,30))

fig, ax = plt.subplots()


plt.scatter(x,y)

plt.savefig('plot.png')

我希望图表显示Favourites 与时间的折线图,其中不同的Users 颜色编码如下例所示:

我目前的输出是这样的:

样本数据

Raw paste

【问题讨论】:

  • 我试过了,输出是 !bizarre
  • 收藏夹数据是什么样的。试试plt.plot(x,y,'ro')
  • 将示例数据添加到主帖

标签: python pandas python-2.7 dataframe matplotlib


【解决方案1】:
df = pd.DataFrame( {'Favorites':['100','200','300'] ,'Date':['02/20/2015','01/15/2016','08/21/2015']})
df['Date'] =pd.to_datetime(df.Date)
df=df.sort_values("Date")
x=df.Date
y=df.Favorites
plt.plot(x,y)
plt.show()

从您提供的图像中,我看到绘图时有锯齿线,试图按日期对数据框进行排序,然后进行绘图。

【讨论】:

    【解决方案2】:

    如果不查看确切数据,很难提供解决方案。也许这值得一试。

    for user in data_frame.User.unique():
         d = data_frame[data_framef['User']==user]
         plt.plot(d['Date'],d['Favourites'],'o')
    
    plt.plot()
    

    【讨论】:

      猜你喜欢
      • 2015-09-10
      • 1970-01-01
      • 2020-06-20
      • 2017-06-28
      • 1970-01-01
      • 2017-08-04
      • 1970-01-01
      • 2021-04-21
      • 2016-06-04
      相关资源
      最近更新 更多