plot - Matplotlib: combining two bar charts -
i'm trying generate 'violin'-like bar charts, i'm running in several difficulties described bellow...
import numpy np import matplotlib.pyplot plt import matplotlib.gridspec 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) 
- trouble adding 'label' labels both charts share.
- centering labels between both plots (as vertically in center of each bar)
- keeping ticks on outer yaxis (not inner, labels go)
if understand question correctly, believe these changes accomplish you're looking for:
import numpy np import matplotlib.pyplot plt import matplotlib.gridspec 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 , 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 second axis tick labels without disturbing originals [lbl.set_visible(false) lbl in ax2.get_yticklabels()] plt.show() this yields plot: 
as keeping actual numerical ticks (if want those), normal matplotlib interface ties ticks pretty closely when axes shared (or twinned). however, axes_grid1 toolkit can allow more control, if want numerical ticks can replace entire ax2 section above following:
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) x in pos]) [lbl.set_visible(false) lbl in ax2.get_yticklabels()] which yields: 
Comments
Post a Comment