第二个y轴和重叠标签?

时间:2016-10-13 11:49:45

标签: python-3.x matplotlib plot

我正在使用python进行卡路里摄入的简单时间序列分析。我正在绘制时间序列和随时间推移的滚动均值/标准。它看起来像这样:enter image description here

我是这样做的:

## packages & libraries
import pandas as pd
import numpy as np
import matplotlib.pylab as plt
from pandas import Series, DataFrame, Panel


## import data and set time series structure
data = pd.read_csv('time_series_calories.csv',  parse_dates={'dates': ['year','month','day']}, index_col=0)


## check ts for stationarity

from statsmodels.tsa.stattools import adfuller
def test_stationarity(timeseries):

    #Determing rolling statistics
    rolmean = pd.rolling_mean(timeseries, window=14)
    rolstd = pd.rolling_std(timeseries, window=14)

    #Plot rolling statistics:
    orig = plt.plot(timeseries, color='blue',label='Original')
    mean = plt.plot(rolmean, color='red', label='Rolling Mean')
    std = plt.plot(rolstd, color='black', label = 'Rolling Std')
    plt.legend(loc='best')
    plt.title('Rolling Mean & Standard Deviation')
    plt.show()

情节看起来并不好 - 因为滚动标准会扭曲变化的规模并且x轴标记被搞砸了。我有两个问题:(1)如何在一个重要的y轴上绘制滚动标准? (2)如何修复x轴重叠标记?

修改

在您的帮助下,我设法获得以下内容: enter image description here

但我能把这个传奇整理出来吗?

1 个答案:

答案 0 :(得分:1)

1)可以使用ax2 = ax1.twinx()制作第二个(双轴)轴,参见here for an example。这是你需要的吗?

2)我相信这个问题有几个旧答案,即hereherehere。根据提供的链接,最简单的方法可能是使用plt.xticks(rotation=70)plt.setp( ax.xaxis.get_majorticklabels(), rotation=70 )fig.autofmt_xdate()

import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([1, 2, 3, 4, 5], [1, 2, 3, 4, 5])
plt.xticks(rotation=70)  # Either this 
ax.set_xticks([1, 2, 3, 4, 5])
ax.set_xticklabels(['aaaaaaaaaaaaaaaa','bbbbbbbbbbbbbbbbbb','cccccccccccccccccc','ddddddddddddddddddd','eeeeeeeeeeeeeeeeee'])
# fig.autofmt_xdate()  # or this
# plt.setp( ax.xaxis.get_majorticklabels(), rotation=70 )  # or this works
fig.tight_layout()
plt.show()

回答编辑 将不同轴之间的线共享到一个图例中时,要在想要将图例设置为轴的轴上创建一些假图:

ax1.plot(something, 'r--')  # one plot into ax1
ax2.plot(something else, 'gx')  # another into ax2

# create two empty plots into ax1
ax1.plot([][], 'r--', label='Line 1 from ax1')  # empty fake-plot with same lines/markers as first line you want to put in legend
ax1.plot([][], 'gx', label='Line 2 from ax2')  # empty fake-plot as line 2 
ax1.legend()

在我的愚蠢示例中,最好在ax1中标记原始图,但我希望你能得到这个想法。重要的是创建"传奇 - 情节"使用与原始图相同的线和标记设置。请注意,由于没有要绘制的数据,因此不会绘制假图。

相关问题