首页 > 解决方案 > 在 1 个图中添加 2 个条形列和 1 个线列

问题描述

我有一个df_daily我想要有 2 列的地方daily_sentiment_polarity,并daily_sentiment_subjectivity作为绘图上的条形和 1 列close作为绘图中的一条线。x 轴应该是变量date

我尝试了以下方法:

df_daily.plot(kind='bar', x='date', y='daily_sentiment_polarity')
df_daily.plot(kind='bar', x='date', y='daily_sentiment_subjectivity')
df_daily.plot(kind='line', x='date', y='close')

但这导致了 3 个单独的地块。有人可以帮我将这 3 个合并为 1 个情节吗?

标签: pythonmatplotlibplotgraph

解决方案


您可以尝试以下方法:

import pandas as pd
import matplotlib.pyplot as plt


data={"date":["01-05-2021","02-05-2021","03-05-2021"],
    'daily_sentiment_polarity':[0,1,0],
    'daily_sentiment_subjectivity':[1,1,0],
    'close':[10,20,5]
}

df_daily=pd.DataFrame(data)
ax=df_daily.plot(kind='bar', x='date', y=['daily_sentiment_polarity','daily_sentiment_subjectivity'])
df_daily.plot(kind='line', x='date', y='close',ax=ax, color='r',secondary_y=True)

plt.show()

结果: 在此处输入图像描述


推荐阅读