0

I have an issue about putting dataframe into to table and saving it as a png file.

To do that, I wrote some code blocks shown below.

df = pd.DataFrame({'count' : fdf.groupby(['year','Name']).size()}).reset_index()
df = df.sort_values(['year','count'], ascending=[True,False]).set_index(['year','Name'])
df = df.style.background_gradient(cmap='YlOrRd')
df

Here is my df

              count
year    Name    
1950    a      3
        b      3
1951    c      3
        d      2
        e      1
...    ...    ...

Then I tried to use this code snippet shown below to save result but it didn't work.

plt.figure(figsize=[15, 15])

ax = plt.subplot()
ax.xaxis.set_visible(False)
ax.yaxis.set_visible(False)
table(ax,f1_df_win_season.data)
plt.savefig('images/image1.png')

Although I can see all variables in table in JupyterNotebook, I couldn't see it in png file.

How can I fix it?

Here is my screenshot

enter image description here

1 Answer 1

1

I would recommend to create a table using the matplotlib 'table' function and do the desired formatting as background gradients afterwards.

After creating the dataframe with

df = pd.DataFrame({'count' : fdf.groupby(['year','Name']).size()}).reset_index()
df = df.sort_values(['year','count'], ascending=[True,False]).set_index(['year','Name'])

you can create (and save) your table like

plt.figure(figsize=[15, 15])

ax = plt.subplot()
ax.xaxis.set_visible(False)
ax.yaxis.set_visible(False)
ax.table(cellText=df.reset_index().values,
        colLabels=df.reset_index().columns,
        loc='center',
        cellLoc='center')
plt.savefig('image1.png')

You can add all the formatting in the table function (see https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.table.html)

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

3 Comments

@Thank you for your response. Because there are 366 values in dataframe , some of them cannot be shown in the image1.png file. How can I fix it?
I guess adding bbox_inches='tight' to plt.savefig will do the trick plt.savefig('image1.png', bbox_inches="tight")
@TonyBrand Your linked question is already solved.

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.