Matplotlib:结合两个条形图

时间:2014-12-10 16:49:50

标签: matplotlib plot bar-chart labels axis-labels

我试图制作类似小提琴的条形图,但是我在下面描述的几个困难中跑步......

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

# init data
label = ['aa', 'b', 'cc', 'd']
data1 = [5, 7, 6, 9]
data2 = [7, 3, 6, 1]
data1_minus = np.array(data1)*-1

gs = gridspec.GridSpec(1, 2, top=0.95, bottom=0.07,)
fig = plt.figure(figsize=(7.5, 4.0))

# adding left bar chart
ax1 = fig.add_subplot(gs[0])
ax1.barh(pos, data1_minus)
ax1.yaxis.tick_right()
ax1.yaxis.set_label(label)

# adding right bar chart
ax2 = fig.add_subplot(gs[1], sharey=ax1)
ax2.barh(pos, data2)

violin-like bar chart

  • 无法添加'标签'作为两个图表的标签分享。
  • 将两个地块之间的标签居中(以及垂直放置在每个酒吧的中心)
  • 只保留外部y轴上的刻度(不是内部,标签可以去的地方)

1 个答案:

答案 0 :(得分:2)

如果我正确理解了这个问题,我相信这些改变能够实现您的目标:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

# init data
label = ['aa', 'b', 'cc', 'd']
data1 = [5, 7, 6, 9]
data2 = [7, 3, 6, 1]
data1_minus = np.array(data1)*-1

gs = gridspec.GridSpec(1, 2, top=0.95, bottom=0.07,)
fig = plt.figure(figsize=(7.5, 4.0))
pos = np.arange(4)

# adding left bar chart
ax1 = fig.add_subplot(gs[0])
ax1.barh(pos, data1_minus, align='center')

# set tick positions and labels appropriately
ax1.yaxis.tick_right()
ax1.set_yticks(pos)
ax1.set_yticklabels(label)
ax1.tick_params(axis='y', pad=15)

# adding right bar chart
ax2 = fig.add_subplot(gs[1], sharey=ax1)
ax2.barh(pos, data2, align='center')

# turn off the second axis tick labels without disturbing the originals
[lbl.set_visible(False) for lbl in ax2.get_yticklabels()]

plt.show()

这会产生这个图:combined bar chart

至于保持实际的数字刻度(如果你想要那些),正常的matplotlib接口在轴共享(或孪生)时将刻度线紧密地联系在一起。但是,axes_grid1工具包可以让您更好地控制,因此如果您想要一些数字刻度,您可以使用以下内容替换上面的整个ax2部分:

from mpl_toolkits.axes_grid1 import host_subplot

ax2 = host_subplot(gs[1], sharey=ax1)
ax2.barh(pos, data2, align='center')
par = ax2.twin()
par.set_xticklabels('')
par.set_yticks(pos)
par.set_yticklabels([str(x) for x in pos])

[lbl.set_visible(False) for lbl in ax2.get_yticklabels()]

产生:combined bar chart with ticks