如何用pyplot在相同的x轴(日期时间)但不同的y轴上绘制线形图和条形图?

时间:2019-02-13 20:52:50

标签: python pandas matplotlib

我试图在同一张图上绘制来自pandas数据框的几列,温度为线性,降雨为条形,它们具有相同的x日期和独立的y比例。

我想出了如何将它们绘制为单独的LINE(XY散点图),它们共享相同的X日期。我也可以玩颜色。最终,我要为温度设置3条线,为雨设置3个栏(条),并使第二个y比例(用于雨)更大,以使条不与温度重叠。 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()

此代码生成带有两个y轴的两个折线图。

enter image description here

如果将其更改为同时绘制vs'DOY _'(整数)而不是“ Fdate”(日期时间)-如果没有DateFormatter件(现在会导致错误,如果包含的话),我可以生成如下的线/条形图。

myDates = doystats['DOY_']
ax2.bar(myDates, myRain, color='b')
#myFmt = mdates.DateFormatter('%b-%d')
#ax1.xaxis.set_major_formatter(myFmt)

enter image description here

解决方法可能是绘制vs“ DOY_”,但不知何故立即从中重新计算日期并将其格式化为MON? 这是数据https://pylab-landviser.notebooks.azure.com/j/edit/PR2_1981-2018_stat.csv的链接 以及整个木星笔记https://pylab-landviser.notebooks.azure.com/j/notebooks/WeatherDaily-Copy.ipynb

1 个答案:

答案 0 :(得分:0)

我最后使用twinx()和twiny()在整数DOY(一年中的某天)第二个x轴(并将其隐藏在显示中)和第二个y轴(将限制设置为30)上绘制条形图以显示降雨情况毫米)。所有温度都绘制在第一个x(格式化的日期时间)和第一个y轴(自动调节到温度范围)上。下面是完整的代码:

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)

使图表如下: Bar and line charts on two sets of XY axes