Home > Back-end >  Matplotlib - Whitespace in Variable used for Filename
Matplotlib - Whitespace in Variable used for Filename

Time:09-11

I am creating several plots using a dataframe. The code looks somewhat like this:

for x in df.col1.unique():
    temp = df_institution.col2.value_counts()
    result = pd.DataFrame(temp)

    plt.bar(result['role'], result['number of nodes'])
    plt.savefig('.plots/political_analysis/institution/'   str(x)   '.png')
    plt.close()

The issue lies in the line where I want to save the plots. Many of the x values have white spaces, for instance 'apple pie'. Of course, when running the code this raises errors. What would be a clever way to bypass this, so I do not have to save each plot individually?

CodePudding user response:

If I am understanding correctly, the problem is the space " " you have in the variable x? If that is the problem, you can simply replace the occurrence of such spaces in x's.

str(x).replace(' ', '_')
  • Related