简体   繁体   English

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

[英]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)

which makes chart below: 如下图所示: 两组XY轴上的条形图和折线图

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

相关问题 如何使用 matplotlib.pyplot 在 x 轴上创建分组条形图(按月和年)并在 y 轴上创建值? - How to create a grouped bar chart (by month and year) on the x-axis and values on the y-axis using matplotlib.pyplot? 堆叠条形图交换 x 轴和 y 轴 - Stacked bar chart swap x-axis and y-axis 创建一个折线图,x 轴为日期时间,y 轴为记录数 - Create a line chart with datetime on x-axis and number of records on y-axis Altair - 将 y 轴与不同图表的 x 轴链接 - Altair - link y-axis with x-axis of a different chart Plot 具有不同的 x 轴和 y 轴使用 matplotlib - Plot with different x-axis and y-axis using matplotlib 在 matplotlib 中使用两个 y 轴格式化 x 轴标签(条形图和折线图) - formatting x-axis labels with two y-axis in matplotlib (bar and line plot) matplotlib 在同一 x 轴上绘制折线图和条形图 - matplotlib plot line and bar chart together on same x-axis 如何在y轴上绘制日期,在x轴上绘制小时? - How to plot date on y-axis and hours on x-axis? python - 如何在x轴上的值范围上制作条形图并计算y轴上的范围? - How to make a bar chart on range of values on x-axis and count on the range on y-axis in python? 如何获得两个折线图(使用单独的y轴)以共享相同的日期x轴? - How to get two line charts (using seperate y-axis), to share the same date x-axis?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM