如何并排绘制具有相同X坐标的条形图('躲闪')

时间:2012-04-29 04:28:36

标签: python matplotlib bar-chart

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 = plt.bar(gridnumber, [0.3, 0.2, 0.2], color="red", width=0.4,
                label="Bar 2", align="center")


plt.ylim([0,0.5])
plt.xlim([0,4])
plt.xticks(gridnumber)
plt.legend()
plt.show()

目前b1和b2相互重叠。我如何单独绘制它们:

enter image description here

5 个答案:

答案 0 :(得分:28)

matplotlib网站中有一个example。基本上,您只需将x值移至width。这是相关的一点:

import numpy as np
import matplotlib.pyplot as plt

N = 5
menMeans = (20, 35, 30, 35, 27)
menStd =   (2, 3, 4, 1, 2)

ind = np.arange(N)  # the x locations for the groups
width = 0.35       # the width of the bars

fig = plt.figure()
ax = fig.add_subplot(111)
rects1 = ax.bar(ind, menMeans, width, color='royalblue', yerr=menStd)

womenMeans = (25, 32, 34, 20, 25)
womenStd =   (3, 5, 2, 3, 3)
rects2 = ax.bar(ind+width, womenMeans, width, color='seagreen', yerr=womenStd)

# add some
ax.set_ylabel('Scores')
ax.set_title('Scores by group and gender')
ax.set_xticks(ind + width / 2)
ax.set_xticklabels( ('G1', 'G2', 'G3', 'G4', 'G5') )

ax.legend( (rects1[0], rects2[0]), ('Men', 'Women') )

plt.show()

答案 1 :(得分:7)

找到正确的条宽有时可能会很棘手。我通常使用此np.diff来找到正确的维度。

import numpy as np
import matplotlib.pyplot as plt

#The data
womenMeans = (25, 32, 34, 20, 25)
menMeans = (20, 35, 30, 35, 27)
indices = [5.5,6,7,8.5,8.9]
#Calculate optimal width
width = np.min(np.diff(indices))/3

fig = plt.figure()
ax = fig.add_subplot(111)
ax.bar(indices-width,womenMeans,width,color='b',label='-Ymin')
ax.bar(indices,menMeans,width,color='r',label='Ymax')
ax.set_xlabel('Test histogram')
plt.show()

结果如下:

enter image description here

如果我的x轴上的索引是名义上的名义值

,该怎么办?
#
import numpy as np
import matplotlib.pyplot as plt

# The data
womenMeans = (25, 32, 34, 20, 25)
menMeans = (20, 35, 30, 35, 27)
indices = range(len(womenMeans))
names = ['Asian','European','North Amercian','African','Austrailian','Martian']
# Calculate optimal width
width = np.min(np.diff(indices))/3.

fig = plt.figure()
ax = fig.add_subplot(111)
ax.bar(indices-width/2.,womenMeans,width,color='b',label='-Ymin')
ax.bar(indices+width/2.,menMeans,width,color='r',label='Ymax')
#tiks = ax.get_xticks().tolist()
ax.axes.set_xticklabels(names)
ax.set_xlabel('Test histogram')
plt.show()

答案 2 :(得分:1)

下面是当您在一个组中有两个以上“类别”时创建并排条形图的两个示例。

手动方法

手动设置每个条的位置和宽度。

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()

enter image description here


熊猫法

如果将数据放入pandas DataFrame中,pandas将为您完成艰巨的任务。

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 

enter image description here

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)

熊猫创造出相似的身材...

enter image description here

答案 3 :(得分:0)

下面的答案将以最简单的方式解释每一行代码:

    <TabBar>
        <Tab Title="Home" Icon="home.png">
            <ShellContent ContentTemplate="{DataTemplate views:DashboardPage}" />
        </Tab>
        <Tab Title="Home" Icon="home.png">
            <ShellContent ContentTemplate="{DataTemplate views:DashboardPage}" />
        </Tab>
        <Tab Title="Home" Icon="home.png">
            <ShellContent ContentTemplate="{DataTemplate views:DashboardPage}" />
        </Tab>
        <Tab Title="Home" Icon="home.png">
            <ShellContent ContentTemplate="{DataTemplate views:DashboardPage}" />
        </Tab>
    </TabBar>

    <FlyoutItem Shell.TabBarIsVisible="True" Title="Info" Icon="home.png">
        <ShellSection>
            <ShellContent ContentTemplate="{DataTemplate views:DashboardPage}"/>
        </ShellSection>
    </FlyoutItem>

    <FlyoutItem Shell.TabBarIsVisible="True" Title="Settings" Icon="card.png">
        <ShellSection>
            <ShellContent ContentTemplate="{DataTemplate views:DashboardPage}"/>
        </ShellSection>
    </FlyoutItem>

enter image description here

答案 4 :(得分:0)

您应该将x数据转换为numpyarray。 enter image description here