Python 将现有绘图添加到轴/子绘图框架中
我有Python 将现有绘图添加到轴/子绘图框架中,python,matplotlib,Python,Matplotlib,我有dfs,例如: import pandas as pd import matplotlib.pyplot as plt import numpy as np df = pd.DataFrame({ 'Country': ["A", "B", "C", "D", "E", "F", "G"], 'Answer declined': [0.000000, 0.000000, 0.000000, 0.000667, 0.000833, 0.000833, 0.000000], "Do
df
s,例如:
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
df = pd.DataFrame({
'Country': ["A", "B", "C", "D", "E", "F", "G"],
'Answer declined': [0.000000, 0.000000, 0.000000, 0.000667, 0.000833, 0.000833, 0.000000],
"Don't know": [0.003333, 0.000000, 0.000000, 0.001333, 0.001667, 0.000000, 0.000000],
"No": [0.769167, 0.843333, 0.762000, 0.666000, 0.721667, 0.721667, 0.775833],
"Yes": [0.227500, 0.156667, 0.238000, 0.332000, 0.275833, 0.277500, 0.224167]}, )
df.set_index("Country", inplace = True)
由于我有多个这样的df
s,我想从中创建绘图,因此我定义了以下函数:
def bar_plot(plot_df):
N = len(plot_df) # number of groups
ind = np.arange(N) # x locations for the groups
width = 0.35 # width of bars
p_s = []
p_s.append(plt.bar(ind, plot_df.iloc[:,0], width))
for i in range(1,len(plot_df.columns)):
p_s.append(plt.bar(ind, plot_df.iloc[:,i], width,
bottom=np.sum(plot_df.iloc[:,:i], axis=1)))
plt.ylabel('[%]')
plt.title('Responses by country')
x_ticks_names = tuple([item for item in plot_df.index])
plt.xticks(ind, x_ticks_names)
plt.yticks(np.arange(0, 1.1, 0.1)) # ticks from, to, steps
#if num_y_cats % 3 == 0: ncol = num_y_cats / 3
#else: ncol = num_y_cats % 3
ncol = 3
plt.legend(p_s, plot_df.columns,
bbox_to_anchor = (0.5, -0.25), # to the left; to the top
loc = 'lower center',
ncol = ncol,
borderaxespad = 0)
plt.show()
plt.close()
调用函数(bar\u plot(df)
)可以得到所需的绘图。然而,我想操纵/微调绘图,因此想将绘图嵌入mpl
图和axe
s
,但未能做到这一点,因为我不知道如何使用p_s=[]
和p_.append(…)
行
有人能帮我找出fig=plt.figure()
,fig.add\u axes()
,以及ax1=fig.add\u子批(111)
的位置吗
非常感谢!:) 您应该从函数中删除最后两行。定义所有图形和子图后,必须调用此行
plt.show()
plt.close()
例如,从函数中删除这些行后,可以使用不同的子批调用函数:
plt.subplot(1,3,1)
bar_plot(df1)
plt.subplot(1,3,2)
bar_plot(df2)
plt.subplot(1,3,3)
bar_plot(df3)
最后:
plt.show()
plt.close()
我想这是可行的。建议的答案确实解决了控制台中显示的绘图问题。但是,对于使用
plt.savefig(filename.png)
保存的文件,命令bbox\u inches='tight'
可以方便地执行以下操作:
plt.savefig(filename.png, bbox_inches='tight')
子图add_sunplot和figure都可以在函数调用之外使用。