4 Python中的Subplot Barcharts

Sam*_*ngG 2 python plot matplotlib subplot

我从matplotlib下载了这个例子并改变了一些东西.

到目前为止,我绘制了一个条形图,其中我在y轴上应用了4个不同的阵列,在x轴上绘制了测量计数.现在我想绘制4个子图,每个子图用于其中一个数组.

我已经到了这一步:

import numpy as np
import matplotlib.pyplot as plt

n= 6

m1 = (0.10,0.12,0.10,0.11,0.14,0.10)
m2=(0.21,0.21,0.20,0.22,0.20,0.21)
m3=(0.29,0.27,0.28,0.24,0.23,0.23)
m4=(0.41,0.39,0.35,0.37,0.41,0.40)
x=[1,2,3,4,5,6]

fig, ax = plt.subplots()

index = np.arange(n)
bar_width = 0.2

opacity = 0.4
error_config = {'ecolor': '0.3'}
r1 = ax.bar(index, m1, bar_width,
                 alpha=opacity,
                 color='b',

                 error_kw=error_config)

r2 = ax.bar(index + bar_width, m2, bar_width,
                 alpha=opacity,
                 color='r',

                 error_kw=error_config)

r3 = ax.bar(index + bar_width+ bar_width, m3, bar_width,
                 alpha=opacity,
                 color='y',
                 error_kw=error_config)
r4 = ax.bar(index + bar_width+ bar_width+ bar_width, m4, bar_width,
                 alpha=opacity,
                 color='c',
                 error_kw=error_config)                 
plt.xlabel('D')
plt.ylabel('Anz')
plt.title('Th')

f, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, sharex='col', sharey='row')

ax1.plot(x,m1)
ax2.plot(x,m2)
ax3.plot(x,m3)
ax4.plot(x,m4)

plt.tight_layout()
plt.show()
Run Code Online (Sandbox Code Playgroud)

为什么我不能只绘制"ax1.plot(x,r1)ax2.plot(x,r2)..."虽然r1,r2被定义为条形,我需要改变什么?

T-8*_*800 5

我希望我不会误解你的问题,答案有助于:

你需要更换ax1.plot(x,r1),并ax2.plot(x,m2)ax1.bar(x,m1, t)ax2.bar(x,m2, t),其中t为任意值,并指示width of the bar.你不能ax1.plot(x,r1),因为r1它已经是一个'酒吧容器'.在这方面:

import numpy as np
import matplotlib.pyplot as plt

n= 6

m1 = (0.10,0.12,0.10,0.11,0.14,0.10)
m2=(0.21,0.21,0.20,0.22,0.20,0.21)
m3=(0.29,0.27,0.28,0.24,0.23,0.23)
m4=(0.41,0.39,0.35,0.37,0.41,0.40)
x=[1,2,3,4,5,6]

fig, ax = plt.subplots()

index = np.arange(n)
bar_width = 0.2

opacity = 0.4
error_config = {'ecolor': '0.3'}
r1 = ax.bar(index, m1, bar_width,
                 alpha=opacity,
                 color='b',

                 error_kw=error_config)

r2 = ax.bar(index + bar_width, m2, bar_width,
                 alpha=opacity,
                 color='r',

                 error_kw=error_config)

r3 = ax.bar(index + bar_width+ bar_width, m3, bar_width,
                 alpha=opacity,
                 color='y',
                 error_kw=error_config)
r4 = ax.bar(index + bar_width+ bar_width+ bar_width, m4, bar_width,
                 alpha=opacity,
                 color='c',
                 error_kw=error_config)                 
plt.xlabel('D')
plt.ylabel('Anz')
plt.title('Th')

f, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, sharex='col', sharey='row')

ax1.bar(x,m1, 0.2) % thickness=0.2
ax2.bar(x,m2, 0.2)
ax3.plot(x,m3)
ax4.plot(x,m4)

plt.tight_layout()
plt.show()
Run Code Online (Sandbox Code Playgroud)