1

I have dfs such as the following:

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)

As I have multiple such dfs from which I want to create plots from, I have defined the below function:

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

calling the function (bar_plot(df)) gives the desired plot. However, I want to manipulate/ fine tune the plots and therefore want to embed the plot into mpl figures and axes but have failed to do so, since I can't figure out how to make it work with the lines p_s = [] and p_s.append(...).

Could someone help me out where the fig = plt.figure(), fig.add_axes(), and ax1 = fig.add_subplot(111) would go?

Thanks a lot! :)

2 Answers 2

1

You should delete the last two lines from your function. This lines must be called after defining all the figures and subplots.

plt.show()
plt.close()

For example, after deleting those lines from the function, you can call the function using different subplots:

plt.subplot(1,3,1)
bar_plot(df1)
plt.subplot(1,3,2)
bar_plot(df2)
plt.subplot(1,3,3)
bar_plot(df3)

And finally:

plt.show()
plt.close()

I suppose this could work.

Sign up to request clarification or add additional context in comments.

1 Comment

Both subplot, add_sunplot, and figure, can be used outside the function call.
0

The suggested answer does address the issue for the shown plot in the console. For the file saved with plt.savefig(filename.png), however, the command bbox_inches='tight' does the trick conveniently:

plt.savefig(filename.png, bbox_inches='tight')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.