Python 如何使用 Pandas 散点图系列
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32791098/
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
How to Scatter Plot Series using Pandas
提问by oscarm
I have this serie:
我有这个系列:
print series.head()
print type(series)
print series.index
year
1992 36.222222
1993 53.200000
1994 49.400000
1995 34.571429
1996 39.200000
Name: ranking, dtype: float64
<class 'pandas.core.series.Series'>
Int64Index([1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014], dtype='int64', name=u'year')
I'm trying to do a scatter plot, but I'm having trouble accessing the the index and values from the series.
我正在尝试绘制散点图,但无法访问系列中的索引和值。
Any pointers will be appreciated.
任何指针将不胜感激。
采纳答案by Dickster
I believe pandas series does not support kind='scatter' if looking t0 call .plot() on a series.
如果在系列上查看 t0 调用 .plot(),我相信熊猫系列不支持 kind='scatter' 。
I believe Lev's answer is best and suitable for use with pandas. I use matplotlib pyplot and it works in similar way to his example.
我相信 Lev 的答案是最好的,适合与熊猫一起使用。我使用 matplotlib pyplot,它的工作方式与他的示例类似。
import matplotlib.pyplot as plt
plt.scatter(ser.index, ser)
plt.show()
Perhaps try this:
也许试试这个:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(1)
year = [1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014]
value = np.random.rand(23)
ser = pd.Series(index = year,data=value)
df =ser.to_frame()
df.reset_index(inplace=True)
df.columns = ['year','value']
df.plot(kind='scatter',x='year',y='value')
plt.show()
回答by Lev Levitsky
Like this?
像这样?
import pylab
pylab.scatter(series.index, series)
回答by bjonen
I think the easiest is:
我认为最简单的是:
For series
系列用
series.plot(style='.')
For dataframe
对于数据框
df.plot(x='x_col', y='y_col', style='.')
回答by Udi Yosovzon
The easiest way I found is to use reset_index()
, it will return a dataframe, with the series index as a column. So this is a very cool way to transfrom a series to a dataframe.
我发现的最简单的方法是使用reset_index()
,它将返回一个数据框,将系列索引作为一列。所以这是从系列转换为数据帧的一种非常酷的方式。
Once you're using a dataframe you can use pandas plot function:
使用数据框后,您可以使用熊猫绘图功能:
df = series.reset_index()
df.plot(x="x_col", y="y_col", kind="scatter")