我想设置一个具有双y轴的图的长宽比,但是到目前为止仍处于figsize
级别,有人可以使用更多axes
实现的其他方法来帮助实现吗?就像使用set_sapect
或plt.gca(subplot_kw={'adjustable':'datalim','aspect':'equal'})
一样,只需开始使用Python学习可视化。下面是一个玩具样本。如果答案还附带我和其他初学者的说明,以了解其内幕内容,那就太好了。
import pandas as pd
import numpy as np
import matplotlib
import matplotlib.pyplot as plt; plt.rcdefaults()
# data preparation
np.random.seed(0)
df = pd.DataFrame(np.random.randint(0,200,size=(100, 2)), columns=['col_1','col_2'])
df['group_l1'] = ['A']*50 + ['B']*50
df['group_l2'] = ['x']*25 + ['y']*25 + ['x']*25 + ['y']*25
# naive benchmark plot
fig, ax = plt.subplots()
ax.plot(df['col_1'])
plt.show()
# ~ 1, single plot
# ~~ 2) two series of data (dual y axis)
fig, ax = plt.subplots()
ax.plot(df.loc[df['group_l1'].isin(['A'])]['col_1'])
ax.set_aspect(1)
ax2 = ax.twinx()
ax2.plot(df.loc[df['group_l1'].isin(['A'])]['col_2'],'r')
ax2.set_aspect(1)
plt.show()
# this won't work anymore, why? maybe because the two y-axis have different limits so python will get confused to set
# a single ratio of two different y units to the same x unit
# a simple workaround in this case
fig, ax = plt.subplots(figsize=(5,5)) # or any other ratio you want.
ax.plot(df.loc[df['group_l1'].isin(['A'])]['col_1'])
ax2 = ax.twinx()
ax2.plot(df.loc[df['group_l1'].isin(['A'])]['col_2'],'r')
plt.show()