pandas 将线添加到熊猫图
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37144219/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Add line to pandas plot
提问by itzy
Using pandas I create a plot of a time series like this:
使用Pandas我创建了一个像这样的时间序列图:
import numpy as np
import pandas as pd
rng = pd.date_range('2016-01-01', periods=60, freq='D')
ts = pd.Series(np.random.randn(len(rng)), index=rng)
ax = ts.plot()
ax.axhline(y=ts.mean(), xmin=-1, xmax=1, color='r', linestyle='--', lw=2)
I would like to add another horizontal line at the level of the mean using only data from February. The mean is just ts.loc['2016-02']
, but how do I add a horizontal line at that level that doesn't go across the whole figure, but only for the dates in February?
我想仅使用 2 月份的数据在均值水平添加另一条水平线。均值只是ts.loc['2016-02']
,但是如何在该级别添加一条水平线,该水平线不会跨越整个数字,而仅适用于 2 月的日期?
回答by piRSquared
Or you can create a new time series whose values are the mean and index only spans February.
或者您可以创建一个新的时间序列,其值为平均值,指数仅跨越 2 月。
ts_feb_mean = ts['2016-02'] * 0 + ts['2016-02'].mean()
All together it looks like:
总而言之,它看起来像:
import numpy as np
import pandas as pd
rng = pd.date_range('2016-01-01', periods=60, freq='D')
ts = pd.Series(np.random.randn(len(rng)), index=rng)
# Feb mean
ts_fm = ts['2016-02'] * 0 + ts['2016-02'].mean()
ts_fm = ts_fm.reindex_like(ts)
# Total mean
ts_mn = ts * 0 + ts.mean()
# better control over ax
fig, ax = plt.subplots(1, 1)
ts.plot(ax=ax)
ts_mn.plot(ax=ax)
ts_fm.plot(ax=ax)
回答by piRSquared
You can use xmin
and xmax
to control where in the chart the line starts and ends. But this is in percent of the chart.
您可以使用xmin
和xmax
来控制图表中线条开始和结束的位置。但这是图表的百分比。
import numpy as np
import pandas as pd
np.random.seed([3, 1415])
rng = pd.date_range('2016-01-01', periods=60, freq='D')
ts = pd.Series(np.random.randn(len(rng)), index=rng)
ts_feb = ts['2016-02']
# used to figure out where to start and stop
ts_len = float(len(ts))
ts_len_feb = float(len(ts_feb))
ratio = ts_len_feb / ts_len
ax = ts.plot()
ax.axhline(y=ts.mean() * 5, xmin=0, xmax=1, color='r', linestyle='--', lw=2)
ax.axhline(y=ts_feb.mean() * 5, xmin=(1. - ratio), xmax=1, color='g', linestyle=':', lw=2)