108

我有一个 pandas 数据框,想绘制一列中的值与另一列中的值。幸运的是,有plot一种与数据框相关的方法似乎可以满足我的需要:

df.plot(x='col_name_1', y='col_name_2')

不幸的是,在绘图样式(在参数后面列出kind似乎没有点。我可以使用线条或条形甚至密度,但不能使用点。是否有解决方法可以帮助解决此问题。

4

4 回答 4

136

您可以style在调用时指定绘制线的df.plot

df.plot(x='col_name_1', y='col_name_2', style='o')

style参数也可以是dictor ,list例如:

import numpy as np
import pandas as pd

d = {'one' : np.random.rand(10),
     'two' : np.random.rand(10)}

df = pd.DataFrame(d)

df.plot(style=['o','rx'])

所有接受的样式格式都列在matplotlib.pyplot.plot.

输出

于 2013-07-23T14:33:45.057 回答
89

为此(以及大多数绘图),我不会依赖 Pandas 包装器来 matplotlib。相反,只需直接使用 matplotlib:

import matplotlib.pyplot as plt
plt.scatter(df['col_name_1'], df['col_name_2'])
plt.show() # Depending on whether you use IPython or interactive mode, etc.

请记住,您可以使用例如访问列值的 NumPy 数组df.col_name_1.values

在具有毫秒精度的时间戳值列的情况下,我在使用 Pandas 默认绘图时遇到了麻烦。在尝试将对象转换为datetime64类型时,我还发现了一个令人讨厌的问题:< Pandas 在询问 Timestamp 列值是否具有 attr astype 时给出了不正确的结果>。

于 2013-07-23T14:36:04.623 回答
7

Pandas用作matplotlib基本图的库。在您的情况下,最简单的方法将使用以下内容:

import pandas as pd
import numpy as np

#creating sample data 
sample_data={'col_name_1':np.random.rand(20),
      'col_name_2': np.random.rand(20)}
df= pd.DataFrame(sample_data)
df.plot(x='col_name_1', y='col_name_2', style='o')

在此处输入图像描述

seaborn但是,如果您想要有更多自定义图而不进入基本级别,我建议您将其用作替代解决方案。matplotlib.在这种情况下,您的解决方案将如下:

import pandas as pd
import seaborn as sns
import numpy as np

#creating sample data 
sample_data={'col_name_1':np.random.rand(20),
      'col_name_2': np.random.rand(20)}
df= pd.DataFrame(sample_data)
sns.scatterplot(x="col_name_1", y="col_name_2", data=df)

在此处输入图像描述

于 2019-06-22T21:29:42.833 回答
0

现在在最新的熊猫中,您可以直接使用 df.plot.scatter 函数

df = pd.DataFrame([[5.1, 3.5, 0], [4.9, 3.0, 0], [7.0, 3.2, 1],
                   [6.4, 3.2, 1], [5.9, 3.0, 2]],
                  columns=['length', 'width', 'species'])
ax1 = df.plot.scatter(x='length',
                      y='width',
                      c='DarkBlue')

https://pandas.pydata.org/pandas-docs/version/0.23/generated/pandas.DataFrame.plot.scatter.html

于 2019-09-20T17:25:09.213 回答