I'm trying to allow my figure to share the same y axis, but have different scales along x axis. The problem is that when I try to map the second figure to the second axes ( ax1 = ax.twiny
), the figure seems to move forward to the right from where it should be. Here is a minimal working example that demonstrates my problem.
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rc
import pandas as pd
r = [0,1,2,3,4]
raw_data = {'greenBars': [20, 1.5, 7, 10, 5], 'orangeBars': [5, 15, 5, 10, 15],'blueBars': [2, 15, 18, 5, 10]}
df = pd.DataFrame(raw_data)
totals = [i+j+k for i,j,k in zip(df['greenBars'], df['orangeBars'], df['blueBars'])]
greenBars = [i / j * 100 for i,j in zip(df['greenBars'], totals)]
f, ax = plt.subplots(1, figsize=(6,6))
ax.barh(r, greenBars, color='#b5ffb9', edgecolor='white', height=0.85)
df = pd.DataFrame({'group':['A', 'B', 'C', 'D', 'E'], 'values':[300,250,150,50,10] })
ax1 = ax.twiny()
ax1.hlines(y=groups, xmin=0, xmax=df['values'], color='black', linewidth=1.5);
plt.show()
where my expected outcome is to have the ax1.hlines
move left-ward to the frame (as shown by the arrows in the image below). Does anybody have any suggestions as to how to fix this behaviour?
barh
usually sets lower limit at 0
while plot
or others set at a little less value for aesthetic. To fix this, manually set xlim for ax1
:
...
f, ax = plt.subplots(1, figsize=(6,6))
ax.barh(r, greenBars, color='#b5ffb9', edgecolor='white', height=0.85)
df = pd.DataFrame({'group':['A', 'B', 'C', 'D', 'E'], 'values':[300,250,150,50,10] })
ax1 = ax.twiny()
ax1.hlines(y=df['group'], xmin=0, xmax=df['values'], color='black', linewidth=1.5);
# this is added
ax1.set_xlim(0)
plt.show()
Output:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.