将现有图添加到轴/子图框架中

时间:2019-03-08 20:08:59

标签: python matplotlib

我有df,例如:

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,因此我定义了以下函数:

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_plot(df))给出所需的图形。但是,我想对图进行调整/微调,因此想将图嵌入到mpl figure s和axe s 中,但没有这样做,因为我无法弄清楚如何使其与行p_s = []p_s.append(...)一起使用。

有人可以帮我解决fig = plt.figure()fig.add_axes()ax1 = fig.add_subplot(111)的去向吗?

非常感谢! :)

2 个答案:

答案 0 :(得分:1)

您应该从函数中删除最后两行。在定义所有图形和子图之后,必须调用此行。

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()

我想这可行。

答案 1 :(得分:0)

建议的答案确实解决了控制台中所示图的问题。但是,对于使用PASS保存的文件,命令plt.savefig(filename.png)可以轻松实现这一目的:

bbox_inches='tight'
相关问题