I'm fairly new to matplotlib
and am limping along. That said, I haven't found an obvious answer to this question.
I have a scatter plot I wanted colored by groups, and it looked like plotting via a loop was the way to roll.
Here is my reproducible example, based on the first link above:
import matplotlib.pyplot as plt
import pandas as pd
from pydataset import data
df = data('mtcars').iloc[0:10]
df['car'] = df.index
fig, ax = plt.subplots(1)
plt.figure(figsize=(12, 9))
for ind in df.index:
ax.scatter(df.loc[ind, 'wt'], df.loc[ind, 'mpg'], label=ind)
ax.legend(bbox_to_anchor=(1.05, 1), loc=2)
# plt.show()
# plt.savefig('file.png')
Uncommenting plt.show()
yields what I want:
Searching around, it looked like plt.savefig()
is the way to save a file; if I re-comment out plt.show()
and run plt.savefig()
instead, I get a blank white picture. This question, suggests this is cause by calling show()
before savefig()
, but I have it entirely commented out. Another question has a comment suggesting I can save the ax
object directly, but that cuts off my legend:
The same question has an alternative that uses fig.savefig()
instead. I get the same chopped legend.
There's this question which seems related, but I'm not plotting a DataFrame
directly so I'm not sure how to apply the answer (where dtf
is the pd.DataFrame
they're plotting):
plot = dtf.plot()
fig = plot.get_figure()
fig.savefig("output.png")
Thanks for any suggestions.
Edit: to test the suggestion below to try tight_layout()
, I ran this and still get a blank white image file:
fig, ax = plt.subplots(1)
plt.figure(figsize=(12, 9))
for ind in df.index:
ax.scatter(df.loc[ind, 'wt'], df.loc[ind, 'mpg'], label=ind)
ax.legend(bbox_to_anchor=(1.05, 1), loc=2)
fig.tight_layout()
plt.savefig('test.png')
plt.tight_layout()
? That might help – Lovelaceplt.savefig()
. If I run that beforeax.figure.savefig()
, it crops to the plot and I lose the legend entirely. – Baecherplt.figure(figsize=(20,10))
– Lovelacesavefig
beforeshow
. (What ispydataset
? Is it needed to reproduce the problem?) – Anagogetight_layout
suggestion. An answer (even if it's just rough) or a gist would be most helpful to make sure we're understanding each other. Namely, in my response I meant to explain that I think I was doing the two in combination. – Baecherpydataset
was the easiest way I found to loadmtcars
. Feel free to suggest another dataset and I can create another example. – Baecherx=[0,1], y=[2,5]
– AnagogeR
wheredata(mtcars)
is pretty standard. I don't know what's common inpython
for this. – Baecherplt.savefig()
experiments worked, thesubplots()
command and adding layers toax
was my main suspect. Thank you for the answer! – Baecher