【问题标题】:Creating a single barplot with different colors with pandas and matplotlib使用 pandas 和 matplotlib 创建具有不同颜色的单个条形图
【发布时间】:2017-12-04 06:58:08
【问题描述】:

我有两个 dfs,我想为其创建一个条形图, 每个条都需要自己的颜色,具体取决于它来自哪个 df。

# Ages < 20
df1.tags = ['locari', 'ママコーデ', 'ponte_fashion', 'kurashiru', 'fashion']
df1.tag_count = [2162, 1647, 1443, 1173, 1032]

# Ages 20 - 24
df2.tags= ['instagood', 'ootd', 'fashion', 'followme', 'love']
df2.tag_count = [6523, 4576, 3986, 3847, 3599]

如何创建这样的情节?

附:原来的df要大得多。有些词可能会重叠,但我希望它们也有不同的颜色

【问题讨论】:

    标签: python-3.x pandas matplotlib


    【解决方案1】:

    您的数据框 tag_counts 只是简单的列表,因此您可以使用标准 mpl 条形图将它们绘制在同一轴上。该答案假定两个数据帧具有相同的长度。

    import matplotlib.pyplot as plt
    import pandas as pd
    import numpy as np
    
    # Create dataframes
    df1=pd.DataFrame()
    df2=pd.DataFrame()
    
    # Ages < 20
    df1.tags = ['locari', 'blub', 'ponte_fashion', 'kurashiru', 'fashion']
    df1.tag_count = [2162, 1647, 1443, 1173, 1032]
    
    # Ages 20 - 24
    df2.tags= ['instagood', 'ootd', 'fashion', 'followme', 'love']
    df2.tag_count = [6523, 4576, 3986, 3847, 3599]
    
    # Create figure
    fig=plt.figure()
    ax=fig.add_subplot(111)
    
    # x-coordinates
    ind1 = np.arange(len(df1.tag_count))
    ind2 = np.arange(len(df2.tag_count))
    width = 0.35
    
    # Bar plot for df1
    ax.bar(ind1,df1.tag_count,width,color='r')
    
    # Bar plot for df1
    ax.bar(ind2+width,df2.tag_count,width,color='b')
    
    # Create new xticks
    ticks=list(ind1+0.5*width)+list(ind2+1.5*width)
    ticks.sort()
    ax.set_xticks(ticks)
    
    # Sort labels in an alternating way
    labels = [None]*(len(df1.tags)+len(df2.tags))
    labels[::2] = df1.tags
    labels[1::2] = df2.tags
    ax.set_xticklabels(labels)
    
    plt.show()
    

    这将返回这样的情节

    请注意,要将两个 tags 合并到一个列表中,我假设两个列表具有相同的长度。

    【讨论】:

      猜你喜欢
      • 2012-07-01
      • 2015-01-03
      • 2019-06-11
      • 1970-01-01
      • 2017-05-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多