在matplotlib中在条形图上并排绘制多个字符串值

时间:2018-07-27 09:12:18

标签: python pandas matplotlib

我有一个数据集

import pandas as pd

compnaies = ['Microsoft', 'Google', 'Amazon', 'Microsoft', 'Facebook', 'Google']
products = ['OS', 'Search', 'E-comm', 'E-comm', 'Social Media', 'OS']
average = [1.2,3.4,2.4,5.2,3.2,4.4]

df = pd.DataFrame({'company' : compnaies, 'product':products,
                    'average' : average})
df

   average  company     product
0   1.2    Microsoft    OS
1   3.4    Google       Search
2   2.4    Amazon       Search
3   5.2    Microsoft    Search
4   4.4    Google       OS

现在我想在Python / MatPlotLib中绘制它 enter image description here

我来自R背景,在这里我发现的所有内容都是将x轴转换为数字索引,然后绘制2个数字值,然后以硬编码方式命名组。是否有标准方法可以绘制所需的图。

在大多数地方,我都找到了类似此代码的帮助,其中我们用静态组绘制了所有数值 https://matplotlib.org/examples/api/barchart_demo.html

1 个答案:

答案 0 :(得分:0)

在此解决方案对我有用时关闭该线程

from matplotlib import pyplot as plt
import pandas as pd

    #create toy dataframe
    np.random.seed(1234)
    df = pd.DataFrame({"clm1": ["X", "Y", "Z", "X", "Y", "Z"], "clm2": np.random.randint(1, 100, 6), "clm3": ["A", "A", "A", "B", "B", "B"]})

    #rearrange dataframe and plot
    df.pivot(index = "clm3", columns = "clm1", values = "clm2").plot.bar(edgecolor = "white")
    plt.xticks(rotation = 0)
    plt.show()

摘自:python plot grouped bar graph