Python 熊猫数据点的线图
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43941245/
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
Line plot with data points in pandas
提问by lincolnfrias
Using pandas
I can easily make a line plot:
使用pandas
I 可以轻松制作线图:
import pandas as pd
import numpy as np
%matplotlib inline # to use it in jupyter notebooks
df = pd.DataFrame(np.random.randn(50, 4),
index=pd.date_range('1/1/2000', periods=50), columns=list('ABCD'))
df = df.cumsum()
df.plot();
But I can't figure out how to also plot the data as points over the lines, as in this example:
但我无法弄清楚如何将数据绘制为线上的点,如本例所示:
This matplotlib exampleseems to suggest the direction, but I can't find how to do it using pandas plotting capabilities. And I am specially interested in learning how to do it with pandas because I am always working with dataframes.
这个 matplotlib 示例似乎暗示了方向,但我找不到如何使用 Pandas 绘图功能来做到这一点。而且我对学习如何使用熊猫特别感兴趣,因为我一直在使用数据框。
Any clues?
有什么线索吗?
回答by tmdavison
You can use the style
kwarg to the df.plot
command. From the docs:
style : list or dict
matplotlib line style per column
风格:列表或字典
每列的 matplotlib 线条样式
So, you could either just set one linestyle for all the lines, or a different one for each line.
因此,您可以只为所有线条设置一种线条样式,也可以为每条线条设置不同的线条样式。
e.g. this does something similar to what you asked for:
例如,这与您要求的类似:
df.plot(style='.-')
To define a different marker and linestyle for each line, you can use a list:
要为每条线定义不同的标记和线型,您可以使用列表:
df.plot(style=['+-','o-','.--','s:'])
You can also pass the markevery
kwarg onto matplotlib
's plot command, to only draw markers at a given interval
您还可以将markevery
kwarg传递到matplotlib
's plot 命令,仅以给定的间隔绘制标记
df.plot(style='.-', markevery=5)
回答by Vinícius Aguiar
You can use markevery
argument in df.plot()
, like so:
您可以使用markevery
参数 in df.plot()
,如下所示:
df = pd.DataFrame(np.random.randn(1000, 4), index=pd.date_range('1/1/2000', periods=1000), columns=list('ABCD'))
df = df.cumsum()
df.plot(linestyle='-', markevery=100, marker='o', markerfacecolor='black')
plt.show()
markevery
would accept a list of specific points(or dates), if that's what you want.
markevery
如果这是您想要的,将接受特定点(或日期)的列表。
You can also define a function to help finding the correct location:
您还可以定义一个函数来帮助找到正确的位置:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame(np.random.randn(1000, 4), index=pd.date_range('1/1/2000', periods=1000), columns=list('ABCD'))
df = df.cumsum()
dates = ["2001-01-01","2002-01-01","2001-06-01","2001-11-11","2001-09-01"]
def find_loc(df, dates):
marks = []
for date in dates:
marks.append(df.index.get_loc(date))
return marks
df.plot(linestyle='-', markevery=find_loc(df, dates), marker='o', markerfacecolor='black')
plt.show()