【问题标题】:Plotting two different values with corresponding date in Pyplot在 Pyplot 中绘制两个具有相应日期的不同值
【发布时间】:2021-11-17 22:43:02
【问题描述】:

我目前正在尝试在折线图上绘制两个不同的值,其对应的日期在 X 轴上。

对于每个日期,我有两个值;比特币价格数据和情绪评分。

以下是数据示例:

date compound price
2018-06-01 0.1601 7541.4501953125
2018-06-02 0.3049 7643.4501953125
2018-06-03 0.296 7720.25
2018-06-04 0.266 7514.47021484375
2018-06-05 0.2533 7633.759765625
2018-06-06 0.2295 7653.97998046875

这已经接近我想要的了: 折线图但日期错误

我对编程很陌生,所以意识到我的代码会非常混乱/效率低下,但这是我迄今为止用来获得上述结果的方法:

fig, ax1 = plt.subplots()

color = 'tab:red'
ax1.set_xlabel('Date')
ax1.set_ylabel('Bitcoin Price (US Dollar)', color=color)

plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
plt.gca().xaxis.set_major_locator(mdates.DayLocator(interval=15))
plt.plot(tweets_normal.date,tweets_normal.price, color=color)
plt.gcf().autofmt_xdate()
ax1.tick_params(axis='y', labelcolor=color)

ax2 = ax1.twinx()  # instantiate a second axes that shares the same x-axis

color = 'tab:blue'
ax2.set_ylabel('Bitcoin Tweet Sentiment', color=color)  # we already handled the x-label with ax1
ax2.plot(tweets_normal.compound, color=color)
ax2.tick_params(axis='y', labelcolor=color)
plt.xticks(rotation=45)

plt.title('Bitcoin price vs Bitcoin Tweet Sentiment')
fig.tight_layout()  # otherwise the right y-label is slightly clipped
plt.show()

我们将不胜感激任何帮助确保日期正确!不知道 1970 年代从何而来

【问题讨论】:

  • 在第二个轴 ax2.plot(tweets_normal.compound, color=color) 中,您没有提供 x 轴的输入,在您的情况下应该是 tweets_normal.date。假设这是您的日期存储位置。试试这个并检查ax2.plot(tweets_normal.date,tweets_normal.compound, color=color)
  • 感谢您的评论 :) 不幸的是,日期看起来都挤在一起了,所以我不确定日期是否真的正确 - link 有什么想法吗?
  • 看起来'date'不是日期时间格式:this is how to plot a dataframe
  • 仅供参考:彻底回答问题非常耗时。如果您的问题已解决,请通过接受最适合您的需求的解决方案表示感谢。 位于答案左上角的 / 箭头下方。如果出现更好的解决方案,则可以接受新的解决方案。如果您的声望超过 15,您也可以使用 / 箭头对答案的有用性进行投票。 如果解决方案不能回答问题,请发表评论What should I do when someone answers my question?。谢谢

标签: python pandas datetime matplotlib data-visualization


【解决方案1】:

首先你应该检查date数据是存储为datetime类型还是str类型,所以看看tweets_normal.info()。你会得到类似的东西:

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 6 entries, 0 to 5
Data columns (total 3 columns):
 #   Column    Non-Null Count  Dtype  
---  ------    --------------  -----  
 0   date      6 non-null      object 
 1   compound  6 non-null      float64
 2   price     6 non-null      float64
dtypes: float64(2), object(1)
memory usage: 272.0+ bytes
None

注意dateDtype:如果是object(所以是str),那么你需要把它转换成datetime,用:

tweets_normal.date = pd.to_datetime(tweets_normal.date, format = '%Y-%m-%d')

现在你应该有:

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 6 entries, 0 to 5
Data columns (total 3 columns):
 #   Column    Non-Null Count  Dtype         
---  ------    --------------  -----         
 0   date      6 non-null      datetime64[ns]
 1   compound  6 non-null      float64       
 2   price     6 non-null      float64       
dtypes: datetime64[ns](1), float64(2)
memory usage: 272.0 bytes
None

所以你已经准备好绘制情节了。
重要的是要指定 matplolitb 您的 x 轴是日期类型,正如您已经正确所做的那样:

plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
plt.gca().xaxis.set_major_locator(mdates.DayLocator(interval=15))

最后,您必须为 axax2 指定 x 和 y 轴(正如 Shubham Shaswat 在问题评论中已经报告的那样):

plt.plot(tweets_normal.date,tweets_normal.price, color=color)

ax2.plot(tweets_normal.date,tweets_normal.compound, color=color)

完整代码

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


tweets_normal = pd.read_csv(r'data/data.csv')
tweets_normal.date = pd.to_datetime(tweets_normal.date, format = '%Y-%m-%d')

fig, ax1 = plt.subplots()

color = 'tab:red'
ax1.set_xlabel('Date')
ax1.set_ylabel('Bitcoin Price (US Dollar)', color=color)

plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
plt.gca().xaxis.set_major_locator(mdates.DayLocator(interval=15))
plt.plot(tweets_normal.date,tweets_normal.price, color=color)
plt.gcf().autofmt_xdate()
ax1.tick_params(axis='y', labelcolor=color)

ax2 = ax1.twinx()  # instantiate a second axes that shares the same x-axis

color = 'tab:blue'
ax2.set_ylabel('Bitcoin Tweet Sentiment', color=color)  # we already handled the x-label with ax1
ax2.plot(tweets_normal.date,tweets_normal.compound, color=color)
ax2.tick_params(axis='y', labelcolor=color)
plt.xticks(rotation=45)

plt.title('Bitcoin price vs Bitcoin Tweet Sentiment')
fig.tight_layout()  # otherwise the right y-label is slightly clipped
plt.show()

【讨论】:

    猜你喜欢
    • 2016-07-31
    • 1970-01-01
    • 2020-09-25
    • 2012-09-23
    • 2021-05-04
    • 2015-08-12
    • 1970-01-01
    • 2011-05-24
    • 2011-10-26
    相关资源
    最近更新 更多