Matplotlib – Whitespace in Variable used for Filename

Question:

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?

Asked By: luthien aerendell

||

Answers:

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(' ', '_')
Answered By: Warkaz
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.