【问题标题】:How to plot line and bar-chart on the same x-axis (datetime) but different y-axis with pyplot?如何使用pyplot在相同的x轴(日期时间)但不同的y轴上绘制折线图和条形图?
【发布时间】:2019-02-13 20:52:50
【问题描述】:

我正在尝试在同一张图上绘制来自 pandas 数据框的几列,温度为线性,雨为条共享相同的 x 日期和单独的 y 尺度。

我想出了如何将它们绘制为单独的 LINE(x-y 散点图)并且它们共享相同的 x 日期。我也可以玩颜色。最终,我想要 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 轴的折线图。

如果我将其更改为同时绘制 vs 'DOY_'(integer) 而不是 "Fdate' (datetime) - 没有 DateFormatter 块(如果包含,现在会导致错误),我可以生成如下线/条形图。

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

解决方法可能是对“DOY_”进行绘图,但以某种方式即时重新计算日期并格式化为 MON? 这是数据的链接https://pylab-landviser.notebooks.azure.com/j/edit/PR2_1981-2018_stat.csv 和整个木星NB https://pylab-landviser.notebooks.azure.com/j/notebooks/WeatherDaily-Copy.ipynb

【问题讨论】:

  • 如何在问题或 cmets 中插入图像?谢谢。
  • 不,它没有。 x 轴采用日期时间格式。
  • ax2.bar() 仅当我在列(整数)DayOfYear 上绘制 x 轴时才有效。但是如何在第一张图片中以特定格式 Mon-01 呈现 x 轴? !dayofyear
  • 您能否在edit 您的帖子中包含一些示例数据并澄清条形图在您使用整数天时有效,但在您使用日期时间时无效?

标签: python pandas matplotlib


【解决方案1】:

我最终使用 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)

下面的图表:

【讨论】:

    猜你喜欢
    • 2020-05-06
    • 2015-09-01
    • 2016-06-24
    • 1970-01-01
    • 2018-01-17
    • 2015-04-04
    • 1970-01-01
    • 2019-06-25
    • 1970-01-01
    相关资源
    最近更新 更多