在 iPython/pandas 中绘制多条线会产生多个图

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28203643/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 22:53:27  来源:igfitidea点击:

Plotting Multiple Lines in iPython/pandas Produces Multiple Plots

pythonmatplotlibpandas

提问by BringMyCakeBack

I am trying to get my head around matplotlib's state machine model, but I am running into an error when trying to plot multiple lines on a single plot. From what I understand, the following code should produce a single plot with two lines:

我试图了解 matplotlib 的状态机模型,但是在尝试在单个图上绘制多条线时遇到错误。据我了解,以下代码应生成一个包含两行的图:

import pandas as pd
import pandas.io.data as web
aapl = web.get_data_yahoo('AAPL', '1/1/2005')

# extract adjusted close
adj_close = aapl.loc[:, ['Adj Close']]

# 2 lines on one plot
hold(False)
adj_close.resample('M', how='min').plot()
adj_close.resample('M', how='max').plot()

In fact, I get three figures: first a blank one, and then two with one line each.

事实上,我得到了三个数字:第一个是空白的,然后是两个,每个数字一行。

blank plotfirst plotsecond plot

空白图第一个情节第二个情节

Any idea what I am doing wrong or what setting on my system might be misconfigured?

知道我做错了什么或者我的系统上的哪些设置可能配置错误?

回答by cstotzer

You can pre-create an axis object using matplotlibs pyplotpackage and then append the plots to this axis object:

您可以使用 matplotlibspyplot包预先创建一个轴对象,然后将绘图附加到这个轴对象:

import pandas as pd
import pandas.io.data as web
import matplotlib.pyplot as plt

aapl = web.get_data_yahoo('AAPL', '1/1/2005')

# extract adjusted close
adj_close = aapl.loc[:, ['Adj Close']]

# 2 lines on one plot
#hold(False)

fig, ax = plt.subplots(1, 1)
adj_close.resample('M', how='min').plot(ax=ax)
adj_close.resample('M', how='max').plot(ax=ax)

Plot example

绘图示例

Alternatively, you could concat the two series into a m x 2 DataFrame and plot the dataframe instead:

或者,您可以将两个系列连接到 amx 2 DataFrame 并绘制数据帧:

s1 = adj_close.resample('M', how='min')
s2 = adj_close.resample('M', how='max')
df = pd.concat([s1, s2], axis=1)
df.plot()