Issues with matplotlib attribute errors - python

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
df = pd.read_csv('Iris.csv')
plot = plt.scatter(df['SepalLengthCm'], df['PetalLengthCm'])
plot.savefig('ScatterIris.png')
I'm trying to do some really basic matplotlib stuff and it keeps raising errors.
C:\Users\Robert\Anaconda3\python.exe
C:/Users/Robert/PycharmProjects/linear_regression/ML.py
Traceback (most recent call last):
File "C:/Users/Robert/PycharmProjects/linear_regression/ML.py", line 9, in <module>
plot.savefig('ScatterIris.png')
AttributeError: 'PathCollection' object has no attribute 'savefig'
First I couldn't use the .show() attribute and then I couldn't use the .savefig() attribute. Is there something wrong with my matplotlib installation?
For reference I tried changing the backend of my matplotib in matplotlibrc to a couple different ones and the same error everytime.
Edit # nbryans
plt.scatter(df['SepalLengthCm'], df['PetalLengthCm']).savefig('ScatterIris.png')
Same error comes up
Edit 2:
Yeah you guys were right I can save figures and use the show() attribute/method.
Thanks!

You need to call pyplot's savefig method.
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
df = pd.read_csv('Iris.csv')
plt.scatter(df['SepalLengthCm'], df['PetalLengthCm'])
plt.savefig('ScatterIris.png')
The same is true if you were using the pandas plotting function,
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
df = pd.read_csv('Iris.csv')
df.plot(kind="scatter", x='SepalLengthCm', y= 'PetalLengthCm')
plt.savefig('ScatterIris.png')

You don't need to assign a plot variable and you should just do plt.show(). Try:
plt.scatter(df['SepalLengthCm'], df['PetalLengthCm'])
plt.savefig('ScatterIris.png') # or plt.show()

This is because savefig() is a function of pyplot (i.e.plt) and not of the recently createdplot`. It saves whatever the current plot you created is. Thus, it should be:
plt.savefig()
Similarly, just to see your plot, it would be
plt.show()

Related

Seaborn Plot is not displaying

I have been trying to plot a simple bar chart using Seaborn. Oddly enough the previous plots worked, but these ones do not appear. No error is being thrown and as far as I can tell the code is okay. Perhaps a more experienced eye will be able to find an error.
import pandas as pd
import numpy as np
import pyodbc
import matplotlib.pyplot as plt
import seaborn as sns
region_pct_25 = region_totals.iloc[0:6, :]
region_pct_25['Opp_Lives_pct'] = ((region_pct_25.Lives / region_pct_25.Lives.sum())*100).round(2)
region_pct_25.reset_index(level=['RegionName'], inplace=True)
region_25_plt = sns.barplot(x="RegionName", y="Opp_Lives_pct", data=region_pct_25, color = 'g').set_title("Client Usage by Region: ADD ")
plt.show()
No plot is showing. Please help wherever you can!
adding %matplotlib inline to the preamble resolved the issue!

How to fix 'NameError: name 'cartopy' is not defined', in plot about sea surface temperature in python?

I'm really new to python, and I need to plot a data netcdf of sea surface temperature(sst),in python, but it keep giving erro.
I use the same code in another notebook, and it run perfect fine.
###SST CĂ“DIGO PLOT
import numpy as np
import matplotlib.pyplot as plt
from numpy import pi
from mpl_toolkits.basemap import Basemap
from netCDF4 import Dataset
import pandas as pd
from scipy import stats
import seaborn as sns
import xarray as xr
import cartopy.crs as ccrs
import os
from netCDF4 import Dataset as netcdf_dataset
from cartopy import config
import statistics
import glob
import seaborn as sns
ds = xr.open_dataset('/home/mayna/Downloads/d86/20190327010000-OSISAF-L3C_GHRSST-SSTsubskin-GOES16-ssteqc_goes16_20190327_010000-v02.0-fv01.0.nc')
plt.figure(figsize=(8,4))
ax = plt.axes(projection=ccrs.PlateCarree())
ax.add_feature(cartopy.feature.BORDERS, linestyle='-', linewidth=0.25)
ax.coastlines(linewidth=0.25)
ds['sea_surface_temperature'][0,:,:].plot.contourf(levels=20, ax=ax, transform=ccrs.PlateCarree(),cmap='coolwarm')
It say that erro is in the line "ax.add_feature(cartopy.feature.BORDERS, linestyle='-', linewidth=0.25)", that "NameError: name 'cartopy' is not defined".
What you think it is the problem?
P.S.: I know that I'm using a lot of lib that don't need
You seem to have never defined cartopy. Perhaps import cartopy at the top would solve your problem.
Name error in python means that the specific attribute/method is not imported in the program. In the code you are using cartopy.crs, cartopy.config and cartopy.features.Border, but only the first two are imported through your statements
import cartopy.crs as crash
and
from cartopy import config
So for features.Border, you either do
import cartopy
Or
from cartopy import features.Border #use just features.Border in that line if you are doing this.
For me, i installed cartopy package in jupyter but still it was showing error of cartopy not defined.(I was plotting the plots with cartopy.ccrs for stereographic plots)
solution: before importing and executing cartopy.ccrs just execute 'import cartopy' in the first line itself and then run the codes.It worked for me

Pycharm: show x/y coordinates with matplotlib automatically

If I plot with ipython, I automatically see the x/y coordinates when I move with the mouse over the canvas (see bottom right in screenshot):
import matplotlib.pyplot as plt
import numpy as np
my_random = np.random.random(5)
plt.plot(my_random)
plt.show()
How can the same achieved with Pycharm (my plots appear in the SciView toolwindow)?
If not: is there perhaps an easy workaround for it? (and do I have more possibilities if the plot does not appear in the SciView toolwindow?)
using TkAgg it works:
import matplotlib
matplotlib.use('TkAgg')
import numpy as np
import matplotlib.pyplot as plt
my_random = np.random.random(5)
plt.plot(my_random)
plt.show()

How to save a Seaborn plot into a file

I tried the following code (test_seaborn.py):
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
matplotlib.style.use('ggplot')
import seaborn as sns
sns.set()
df = sns.load_dataset('iris')
sns_plot = sns.pairplot(df, hue='species', size=2.5)
fig = sns_plot.get_figure()
fig.savefig("output.png")
#sns.plt.show()
But I get this error:
Traceback (most recent call last):
File "test_searborn.py", line 11, in <module>
fig = sns_plot.get_figure()
AttributeError: 'PairGrid' object has no attribute 'get_figure'
I expect the final output.png will exist and look like this:
How can I resolve the problem?
The following calls allow you to access the figure (Seaborn 0.8.1 compatible):
swarm_plot = sns.swarmplot(...)
fig = swarm_plot.get_figure()
fig.savefig("out.png")
as seen previously in this answer.
The suggested solutions are incompatible with Seaborn 0.8.1. They give the following errors because the Seaborn interface has changed:
AttributeError: 'AxesSubplot' object has no attribute 'fig'
When trying to access the figure
AttributeError: 'AxesSubplot' object has no attribute 'savefig'
when trying to use the savefig directly as a function
UPDATE:
I have recently used PairGrid object from seaborn to generate a plot similar to the one in this example.
In this case, since GridPlot is not a plot object like, for example, sns.swarmplot, it has no get_figure() function.
It is possible to directly access the matplotlib figure by:
fig = myGridPlotObject.fig
Some of the above solutions did not work for me. The .fig attribute was not found when I tried that and I was unable to use .savefig() directly. However, what did work was:
sns_plot.figure.savefig("output.png")
I am a newer Python user, so I do not know if this is due to an update. I wanted to mention it in case anybody else runs into the same issues as I did.
Fewer lines for 2019 searchers:
import matplotlib.pyplot as plt
import seaborn as sns
df = sns.load_dataset('iris')
sns_plot = sns.pairplot(df, hue='species', height=2.5)
plt.savefig('output.png')
UPDATE NOTE: size was changed to height.
You should just be able to use the savefig method of sns_plot directly.
sns_plot.savefig("output.png")
For clarity with your code if you did want to access the matplotlib figure that sns_plot resides in then you can get it directly with
fig = sns_plot.fig
In this case there is no get_figure method as your code assumes.
I use distplot and get_figure to save picture successfully.
sns_hist = sns.distplot(df_train['SalePrice'])
fig = sns_hist.get_figure()
fig.savefig('hist.png')
I couldnt get the other answers to work and finally got this to work for me for matplotlib==3.2.1 . Its especially true if you are doing this within a for loop or some iterative approach.
sns.scatterplot(
data=df_hourly, x="date_week", y="value",hue='variable'
)
plt.savefig('./f1.png')
plt.show()
Note that the savefig must be before the show call. Otherwise an empty image is saved.
This works for me
import seaborn as sns
import matplotlib.pyplot as plt
%matplotlib inline
sns.factorplot(x='holiday',data=data,kind='count',size=5,aspect=1)
plt.savefig('holiday-vs-count.png')
Its also possible to just create a matplotlib figure object and then use plt.savefig(...):
from matplotlib import pyplot as plt
import seaborn as sns
import pandas as pd
df = sns.load_dataset('iris')
plt.figure() # Push new figure on stack
sns_plot = sns.pairplot(df, hue='species', size=2.5)
plt.savefig('output.png') # Save that figure
You would get an error for using sns.figure.savefig("output.png") in seaborn 0.8.1.
Instead use:
import seaborn as sns
df = sns.load_dataset('iris')
sns_plot = sns.pairplot(df, hue='species', size=2.5)
sns_plot.savefig("output.png")
Just FYI, the below command worked in seaborn 0.8.1 so I guess the initial answer is still valid.
sns_plot = sns.pairplot(data, hue='species', size=3)
sns_plot.savefig("output.png")

plot, figure, and title function error

I'm having trouble plotting my results in Python, both in Ubuntu 14 and Windows 7 (both 64bit). As a simple comparison I did:
from tvb.simulator.lab import *
--> to import (among others) numpy as np and matplotlib.pyplot.
x = [1,2,3]
plot(x)
--> NameError: name 'plot' is not defined
When I looked up this error (plot is not defined) and followed these instructions, I get this result
matplotlib.lines.Line2D object at 0x7f8e31754dd0
without output...
Anyone who knows how I can fix this?
Assuming that your import (tvb.simulator.lab) does
import numpy as np
import matplotlib.pyplot
then you have to call plot like this:
matplotlib.pyplot.plot(x)
BUT, you could also reimport it in your script:
import matplotlib.pyplot as plt
and then use the alias plt (thats farely common):
plt.plot(x)

Categories

Resources