[英]How to plot line and bar-chart on the same x-axis (datetime) but different y-axis with pyplot?
I am trying to plot several columns from pandas dataframe on the same graph, temperature as linear and rain as bars sharing the same x-Date and separate y-scales. 我正在尝试在同一张图表上绘制来自pandas数据框的几列,温度为线性,降雨为条形,它们共享相同的x日期和单独的y比例。
I figured out how to plot them as separate LINE (xy scatter) and they share the same x-date. 我想出了如何将它们绘制为单独的LINE(xy散点图),它们共享相同的x日期。 I can play with colors too.
我也可以玩颜色。 Eventually, I want 3 lines for temperatures and columns(bars) for rain and make second y-scale (for rain) bigger so the bars not overlapping with Temperatures.
最终,我要为温度设置3条线,为雨设置3个栏(条),并使第二个y比例(用于雨)更大,以使条不与温度重叠。 Is it possible with pyplot?
pyplot可以吗?
import matplotlib.dates as mdates
import matplotlib.pyplot as plt
fig, ax1 = plt.subplots()
myDates = doystats['Fdate']
myValues = doystats['T2M_mean']
ax1.plot(myDates, myValues, 'g')
ax1.set_xlabel('Dates')
# Make the y-axis label, ticks and tick labels match the line color.
ax1.set_ylabel('Temperature, C')
ax1.tick_params('y', colors='g')
ax2 = ax1.twinx()
myRain = doystats['PRECTOT_mean']
ax2.plot(myDates, myRain, color='b')
ax2.set_ylabel('Precipitation, mm', color='b')
ax2.tick_params('y', colors='b')
myFmt = mdates.DateFormatter('%b-%d')
ax1.xaxis.set_major_formatter(myFmt)
fig.tight_layout()
plt.show()
this code produces two line graphs with two y-axes. 此代码生成带有两个y轴的两个折线图。
If I change it to plot both vs 'DOY_'(integer) instead of "Fdate' (datetime) - without DateFormatter piece (that results in error now, if included), I can produce line/bar graph as below. 如果我更改它以绘制两个vs'DOY _'(整数)而不是“ Fdate”(日期时间)-如果没有DateFormatter件(现在会导致错误,如果包含的话),我可以生成如下的线/条形图。
myDates = doystats['DOY_']
ax2.bar(myDates, myRain, color='b')
#myFmt = mdates.DateFormatter('%b-%d')
#ax1.xaxis.set_major_formatter(myFmt)
The workaround maybe to plot vs "DOY_" but somehow recalculate date from it on the fly and format as MON? 解决方法可能是绘制vs“ DOY_”,但以某种方式即时重新计算日期并将其格式化为MON? Here is the link to the data https://pylab-landviser.notebooks.azure.com/j/edit/PR2_1981-2018_stat.csv and to the whole Jupiter NB https://pylab-landviser.notebooks.azure.com/j/notebooks/WeatherDaily-Copy.ipynb
这是数据https://pylab-landviser.notebooks.azure.com/j/edit/PR2_1981-2018_stat.csv和整个Jupiter NB的链接https://pylab-landviser.notebooks.azure.com/焦耳/笔记本/ WeatherDaily-Copy.ipynb
I ended up using twinx() and twiny() to plot bar graph for rain on integer DOY (day of the year) second x-axis (and hide it in the display) and second y axis (set limit to 30 mm). 我最终使用twinx()和twiny()在第二个x轴(并将其隐藏在显示中)和第二个y轴(将限制设置为30毫米)上在整数DOY(一年中的某天)上绘制降雨的条形图。 All temperatures are plotted on first x (formatted datetime) and first y axes (self-adjusting to the temperature range).
所有温度都绘制在第一个x(格式化的日期时间)和第一个y轴(自动调节到温度范围)上。 Below is full code:
下面是完整的代码:
matplotlib.rc('figure', figsize=(12, 5)) # this is to overwrite default aspect of graph to make x-axis longer
fig, ax1 = plt.subplots()
# data to be plotted from dataframe - temperatures as line graphs
Dates = doystats['Fdate']
Tmean = doystats['T2M_mean']
Tmax = doystats['T2M_MAX_mean']
Tmin = doystats['T2M_MIN_mean']
ax1.plot(Dates, Tmean, 'g', Dates, Tmax, 'r', Dates, Tmin, 'k')
# Make the y-axis label
ax1.set_ylabel('Temperature (C)')
ax1.tick_params('y')
# Creating twin axes for precipitation as a bar graph on secondary XY axes
ax2 = ax1.twiny()
ax3 = ax2.twinx()
#data for bar graph
doy = doystats['DOY_']
myRain = doystats['PRECTOT_mean']
ax3.bar(doy, myRain, color='b')
ax2.set_xticks([]) # to hide ticks on the second X-axis - top of the graph
ax3.set_ylabel('Precipitation (mm)', color='b')
ax3.tick_params('y', colors='b')
ax3.set_ylim(top=30)
# Formatting Date X-axis with monthly scale
months = mdates.MonthLocator() # every month
days = mdates.DayLocator() # every day
myFmt = mdates.DateFormatter('%b')
ax1.xaxis.set_major_locator(months)
ax1.xaxis.set_major_formatter(myFmt)
ax1.xaxis.set_minor_locator(days)
# Formatting second X-axis (DOY integers) to disappear
ax2.xaxis.set_major_formatter(plt.NullFormatter())
# Displaying grid for the Date axis
ax1.grid(True)
fig.tight_layout()
# Saving graph to file
plt.savefig(filename + '_annual.png',dpi=300,transparent=True)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.