简体   繁体   English

熊猫数据框绘图-从两个子图切换到带有辅助轴的单个图时出现的问题

[英]Pandas dataframe plotting - issue when switching from two subplots to single plot w/ secondary axis

I have two sets of data I want to plot together on a single figure. 我有两组数据想在一个图形上绘制在一起。 I have a set of flow data at 15 minute intervals I want to plot as a line plot, and a set of precipitation data at hourly intervals, which I am resampling to a daily time step and plotting as a bar plot. 我有一组以15分钟为间隔绘制的流量数据,要绘制为线形图,还有一组以小时为间隔的降水数据,我将这些数据重新采样为每天的时间步长,并绘制为条形图。 Here is what the format of the data looks like: 数据格式如下所示:

2016-06-01 00:00:00             56.8
2016-06-01 00:15:00             52.1
2016-06-01 00:30:00             44.0
2016-06-01 00:45:00             43.6
2016-06-01 01:00:00             34.3

At first I set this up as two subplots, with precipitation and flow rate on different axis. 首先,我将其设置为两个子图,降水和流速在不同的轴上。 This works totally fine. 这完全正常。 Here's my code: 这是我的代码:

import matplotlib.pyplot as plt
import pandas as pd
from datetime import datetime

filename = 'manhole_B.csv'
plotname = 'SSMH-2A B'
plt.style.use('bmh')

# Read csv with precipitation data, change index to datetime object
pdf = pd.read_csv('precip.csv', delimiter=',', header=None, index_col=0)
pdf.columns = ['Precipitation[in]']
pdf.index.name = ''
pdf.index = pd.to_datetime(pdf.index)
pdf = pdf.resample('D').sum()
print(pdf.head())

# Read csv with flow data, change index to datetime object
qdf = pd.read_csv(filename, delimiter=',', header=None, index_col=0)
qdf.columns = ['Flow rate [gpm]']
qdf.index.name = ''
qdf.index = pd.to_datetime(qdf.index)


# Plot
f, ax = plt.subplots(2)
qdf.plot(ax=ax[1], rot=30)
pdf.plot(ax=ax[0], kind='bar', color='r', rot=30, width=1)

ax[0].get_xaxis().set_ticks([])
ax[1].set_ylabel('Flow Rate [gpm]')
ax[0].set_ylabel('Precipitation [in]')
ax[0].set_title(plotname)
f.set_facecolor('white')
f.tight_layout()
plt.show()

2 Axis Plot 2轴图

However, I decided I want to show everything on a single axis, so I modified my code to put precipitation on a secondary axis. 但是,我决定将所有内容显示在一个轴上,因此我修改了代码以将降水量放置在第二个轴上。 Now my flow data data has disppeared from the plot, and even when I set the axis ticks to an empty set, I get these 00:15 00:30 and 00:45 tick marks along the x-axis. 现在,我的流量数据数据从图中消失了,即使将轴刻度设置为空集,我也会沿x轴获得这些00:15 00:30和00:45刻度。

Secondary-y axis plots 次要Y轴图

Any ideas why this might be occuring? 有什么想法可能会发生这种情况吗?

Here is my code for the single axis plot: 这是我的单轴绘图代码:

f, ax = plt.subplots()
qdf.plot(ax=ax, rot=30)
pdf.plot(ax=ax, kind='bar', color='r', rot=30, secondary_y=True)
ax.get_xaxis().set_ticks([])

Here is an example: 这是一个例子:

Setup 设定

In [1]: from matplotlib import pyplot as plt
        import pandas as pd
        import numpy as np
        %matplotlib inline

        df = pd.DataFrame({'x'  : np.arange(10),
                           'y1' : np.random.rand(10,),
                           'y2' : np.square(np.arange(10))})
        df

Out[1]:     x   y1          y2
        0   0   0.451314    0
        1   1   0.321124    1
        2   2   0.050852    4
        3   3   0.731084    9
        4   4   0.689950    16
        5   5   0.581768    25
        6   6   0.962147    36
        7   7   0.743512    49
        8   8   0.993304    64
        9   9   0.666703    81

Plot 情节

In [2]: fig, ax1 = plt.subplots()
        ax1.plot(df['x'], df['y1'], 'b-')
        ax1.set_xlabel('Series')
        ax1.set_ylabel('Random', color='b')
        for tl in ax1.get_yticklabels():
            tl.set_color('b')
        ax2 = ax1.twinx() # Note twinx, not twiny. I was wrong when I commented on your question.
        ax2.plot(df['x'], df['y2'], 'ro')
        ax2.set_ylabel('Square', color='r')
        for tl in ax2.get_yticklabels():
            tl.set_color('r')
Out[2]: 

情节

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

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