Matplotlib: combining two histograms

I am trying to create "violin" histograms, however I am running into a few difficulties described below ...

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

  • Problem adding label for labels for both graphs.
  • Centering the labels between both graphs (and also vertically in the center of each panel)
  • Saving only ticks on the external yaxis (not inside where the labels will be displayed)
+3


source to share


1 answer


If I understand the question correctly, I believe these changes accomplish what you are looking for:

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

      

This gives this graph: combined bar chart



As for storing actual numeric ticks (if you want to), the normal matplotlib interface links ticks close together when the axes are shared (or doubled). However, the axes_grid1 toolkit may allow you more control, so if you need some numeric ticks, you can replace the entire section ax2

above with:

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

      

which gives: combined bar chart with ticks

+2


source







All Articles