Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Matplotlib – Whitespace in Variable used for Filename

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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(' ', '_')
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading