首页 > 解决方案 > 在 Pyplot 中绘制两个具有相应日期的不同值

问题描述

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

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

以下是数据示例:

日期 化合物 价格
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 年代从何而来

标签: pythonpandasdatetimematplotlibdata-visualization

解决方案


首先,您应该检查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

注意date Dtype:如果是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))

最后,您必须为两者指定 x 和 y 轴axax2正如 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()

在此处输入图像描述


推荐阅读