How to plot bar graphs with same X coordinates side by side ('dodged')

后端 未结 5 1870
慢半拍i
慢半拍i 2020-12-05 02:12
import matplotlib.pyplot as plt

gridnumber = range(1,4)

b1 = plt.bar(gridnumber, [0.2, 0.3, 0.1], width=0.4,
                label=\"Bar 1\", align=\"center\")

b2         


        
5条回答
  •  悲哀的现实
    2020-12-05 02:43

    Here are two examples of creating a side-by-side bar chart when you have more than two "categories" in a group.

    Manual Method

    Manually set the position and width of each bar.

    import numpy as np
    import matplotlib.pyplot as plt
    from matplotlib import ticker
    
    coins = ['penny', 'nickle', 'dime', 'quarter']
    worth = np.array([.01, .05, .10, .25])
    
    # Coin values times *n* coins
    #    This controls how many bars we get in each group
    values = [worth*i for i in range(1,6)]
    
    n = len(values)                # Number of bars to plot
    w = .15                        # With of each column
    x = np.arange(0, len(coins))   # Center position of group on x axis
    
    for i, value in enumerate(values):
        position = x + (w*(1-n)/2) + i*w
        plt.bar(position, value, width=w, label=f'{i+1}x')
    
    plt.xticks(x, coins);
    
    plt.ylabel('Monetary Value')
    plt.gca().yaxis.set_major_formatter(ticker.FormatStrFormatter('$%.2f'))
    
    plt.legend()
    


    Pandas Method

    If you put the data into a pandas DataFrame, pandas will do the hard stuff for you.

    import pandas as pd
    coins = ['penny', 'nickle', 'dime', 'quarter']
    worth = [0.01, 0.05, 0.10, 0.25]
    df = pd.DataFrame(worth, columns=['1x'], index=coins)
    df['2x'] = df['1x'] * 2 
    df['3x'] = df['1x'] * 3 
    df['4x'] = df['1x'] * 4 
    df['5x'] = df['1x'] * 5 
    

    from matplotlib import ticker
    import matplotlib.pyplot as plt
    
    df.plot(kind='bar')
    
    plt.ylabel('Monetary Value')
    plt.gca().yaxis.set_major_formatter(ticker.FormatStrFormatter('$%.2f'))
    plt.gca().xaxis.set_tick_params(rotation=0)
    

    Pandas creates a similar figure...

提交回复
热议问题