使用 matplotlib twiny 创建相同的轴
Creating identical axes with matplotlib twiny
我正在尝试复制我的 y 轴,以便它出现在我的图表的左侧和右侧(每侧的比例相同)。我相信正确的方法是通过 twiny 方法,但我无法理解它。这是我当前的代码:
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
def bar(data_df,
colour_df=None,
method='default',
ret_obj=False):
height = len(data_df.columns)*4
width = len(data_df.index)/4
ind = np.arange(len(data_df.index))
dat = data_df[data_df.columns[0]]
bar_width = 0.85
fig, ax = plt.subplots(figsize=(width,height))
ax1 = ax.bar(ind,dat,bar_width,color='y',log=True)
ax2 = ax1.twiny()
ax.tick_params(bottom='off', top='off', left='on', right='on')
plt.xticks(np.arange(len(data_df.index)) + bar_width,
data_df.index, rotation=67,ha='right')
ylab = 'Region Length (base pairs, log10)'
figname = 'bar' + method + '.png'
if ret_obj==False:
fig.savefig(figname,bbox_inches='tight',dpi=250)
print "Output figure:", figname
plt.close()
if ret_obj==True:
return fig
其中returns传递数据帧时出现以下错误:
AttributeError: 'BarContainer' object has no attribute 'twiny'
进一步研究后,我相信使用 host/parasite methods 也可以,但我有点不知道如何将它融入我当前的代码。不胜感激!
在这种情况下您不必使用 twiny
。在所有边上绘制标签就足够了:
bars = ax.bar(ind,dat,bar_width,color='y',log=True)
ax.tick_params(axis='both', which='both', labelbottom=True, labeltop=True,
labelleft=True, labelright=True)
我使用虚拟数据得到以下结果:
df = pd.DataFrame({"a": np.logspace(1,10,20)})
bar(df)
我正在尝试复制我的 y 轴,以便它出现在我的图表的左侧和右侧(每侧的比例相同)。我相信正确的方法是通过 twiny 方法,但我无法理解它。这是我当前的代码:
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
def bar(data_df,
colour_df=None,
method='default',
ret_obj=False):
height = len(data_df.columns)*4
width = len(data_df.index)/4
ind = np.arange(len(data_df.index))
dat = data_df[data_df.columns[0]]
bar_width = 0.85
fig, ax = plt.subplots(figsize=(width,height))
ax1 = ax.bar(ind,dat,bar_width,color='y',log=True)
ax2 = ax1.twiny()
ax.tick_params(bottom='off', top='off', left='on', right='on')
plt.xticks(np.arange(len(data_df.index)) + bar_width,
data_df.index, rotation=67,ha='right')
ylab = 'Region Length (base pairs, log10)'
figname = 'bar' + method + '.png'
if ret_obj==False:
fig.savefig(figname,bbox_inches='tight',dpi=250)
print "Output figure:", figname
plt.close()
if ret_obj==True:
return fig
其中returns传递数据帧时出现以下错误:
AttributeError: 'BarContainer' object has no attribute 'twiny'
进一步研究后,我相信使用 host/parasite methods 也可以,但我有点不知道如何将它融入我当前的代码。不胜感激!
在这种情况下您不必使用 twiny
。在所有边上绘制标签就足够了:
bars = ax.bar(ind,dat,bar_width,color='y',log=True)
ax.tick_params(axis='both', which='both', labelbottom=True, labeltop=True,
labelleft=True, labelright=True)
我使用虚拟数据得到以下结果:
df = pd.DataFrame({"a": np.logspace(1,10,20)})
bar(df)