python - 带计数的 Matplotlib 折线图?

标签 python matplotlib

我正在尝试绘制一个大型数据集的折线图,我想在其中将 y 设置为“计数”值。

这是一个模拟 df :

my = pd.DataFrame(np.array(
   [['Apple', 1], 
    ['Kiwi',  2],
    ['Clementine', 3],
    ['Kiwi', 1], 
    ['Banana',  2], 
    ['Clementine', 3],
    ['Apple',  1], 
    ['Kiwi',  2]]), 
                    columns=['fruit', 'cheers'])

我希望情节使用“干杯”作为 x,然后为每个“水果”和“干杯”次数设置一行

编辑:折线图可能不是最好的追求,请给我建议。我想要这样的东西: enter image description here

在大数据集中可能会有一个但不是几个“零”,也许我应该做一个更大的模拟 df。

最佳答案

我看到你已经接受了一个答案,但是另一种方法是这样的

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

my = pd.DataFrame(np.array([['Apple', 1],
                            ['Kiwi',  2],
                            ['Clementine', 3],
                            ['Kiwi', 1],
                            ['Banana',  2],
                            ['Clementine', 3],
                            ['Apple',  1],
                            ['Kiwi',  2]]),
                  columns=['fruit', 'cheers'])

my_pivot = my.pivot_table(index = 'cheers', 
                          columns = 'fruit', 
                          fill_value = 0, 
                          aggfunc={'fruit':len})['fruit']
my_pivot.plot.line()
plt.tight_layout()
plt.show()

输出:

line plot of pivot table

关于python - 带计数的 Matplotlib 折线图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56181597/

相关文章:

python - 将字符串中的十六进制字符附加到字符串

python - Python 是否支持自由间距的正则表达式?

python - sklearn.plot_tree 如何可视化分类任务的 class_labels?

Python:在一张图中绘制所有分类子集组合

python - 如何向具有多个变量的散点图添加标签?

python - 从 tzdata 中提取历史闰秒

Python NameError The class of the name is not defined 但实际上是

python - 在 python 中打印断言的成功消息

python - 如何绘制两个数据点序列之间的点对点对齐?

python - 如何将所有图例条目放在一行上?