简体   繁体   English

如何 plot 与 matplotlib 在同一图表中平行的第二条杆

[英]How to plot a second bar parallel in the same chart with matplotlib

How can I plot a second bar parallel in the same chart?我怎样才能 plot 在同一图表中平行的第二条? I would like to plot a second bar in red parallel to the green bar in the following chart:df_strat_out["2-down"]我想 plot 与下图中的绿色条平行的第二条红色条:df_strat_out["2-down"]

import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import pandas as pd
df1 = pd.DataFrame()
index = ['2020-01-01','2020-01-08','2020-01-15','2020-01-22','2020-01-29']
df1 = pd.DataFrame(index = index)
upbars = ['2','3','2','4','5']
downbars = ['2','3','2','4','5']
df1['2-up'] = upbars
df1['2-down'] = downbars
df1
df_strat_out = df1
dates_index = df_strat_out.index
up = df_strat_out["2-up"]
down = df_strat_out["2-down"]
width = 0.2       # the width of the bars: can also be len(x) sequence
fig, ax = plt.subplots(figsize=(10, 5))
ax1 = ax.twinx()
ax.bar(dates_index, up, width, label='2-up',color='g')
# ax.bar(dates_index, down, width, bottom=up,label='2-down',color='r')
ax1.plot(dates_index, up, color='b')
# ax1.grid(b=False)
ax.set_ylabel('Scores')
ax.set_title('TheStrat Stats 2-up 2-down')
ax.legend()
#plt.xticks(rotation = 90) # Rotates X-Axis Ticks by 45-degrees
for tick in ax.get_xticklabels():
tick.set_rotation(90)
plt.show()

You can just use the pandas inbuilt plotting functionality if you want to plot it side-by-side.如果您想并排使用 plot,您可以使用pandas内置plotting功能。

import pandas as pd
import matplotlib.pyplot as plt

plotdata = pd.DataFrame({
    "upbars":[2,3,2,4,5],
    "downbars":[2,3,2,4,5]
    }, 
    index=['2020-01-01','2020-01-08','2020-01-15','2020-01-22','2020-01-29']
)
plotdata.plot(kind="bar")
# plt.plot(dates_index, up, color='b') # if you need your line
plt.title("Title")
plt.xlabel("X label")
plt.ylabel("Y label")

输出1

If you also need you blue line, just uncomment the line.如果您还需要蓝线,只需取消注释该行。

PS : I converted your string values to numbers. PS :我将您的字符串值转换为数字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM