Python pandas : pd.options.display.mpl_style = 'default' causes graph crash - python

Everything is in the title. My graph is displayed properly when I do not set this option at the beginning of my python script, otherwise it opens the window for the graph but closes it straightback and end the run.
I am using pandas 0.14.0 and matplotlib 1.3.0.
Anyone already saw this ? You can see my code below if needed.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
#pd.options.display.mpl_style = 'default'
df = pd.DataFrame(np.random.randn(1000, 4), index=pd.date_range('1/1/2000',periods=1000), columns=list('ABCD'))
df = df.cumsum()
df.plot(legend=False)
plt.show()

I was experiencing a similar error with Matplotlib v1.4. The solution I found is to use
matplotlib.style.use('ggplot')
rather than
pd.options.display.mpl_style = 'default'
See - https://pandas-docs.github.io/pandas-docs-travis/visualization.html

Use the following:
plt.show(block=True)

Related

Result image not showing in VSCode

Im trying to visualize the data using python in VSCode, the code is down below
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
train_df = pd.read_csv('D:/GBM project/train_labels.csv')
plt.figure(figsize = (5, 5))
sns.countplot(data = train_df, x = 'MGMT_value')
This code run successfully but no image is shown, could someone tells me where's the problem?
Thanks in advance!
Maybe it's closing after running successfully. If you're not getting any exceptions after code execution, try following things
add temp=input() at the end of the program
add plt.show() at the end of the program
add sns.set_theme() before last line

How do I render Python plots in RMarkdown?

For the life of me, I can't get to render plots in RMarkdown using Python. The plots display in my Python Editor, but not when I switch to RStudio trying to build a PDF/HTML report. I've been all over the internet, everyone has an answer, but none has the solution to my issue. Here's the error message I get the attached error below:
Below I made up some data to show what I'm trying to achieve. Once the application hits the seaborn line it produces the attached error message in RStudio
knitr::opts_chunk$set(echo = TRUE)
library(reticulate)
Importing Required Packages
import pandas as pd
import numpy as np
from scipy.stats import uniform # for training-and-test split
import statsmodels.api as sm # statistical models (including regression)
import statsmodels.formula.api as smf # R-like model specification
import matplotlib.pyplot as plt # 2D plotting
import seaborn as sns
x = np.random.normal(0, 1, 20)
y = np.random.normal(0, 2, 20)
sns.scatterplot(x, y)
I found the answer here
All I needed was to add these two lines in the R setup chunk below the library(reticulate) call
matplotlib <- import("matplotlib")
matplotlib$use("Agg", force = TRUE)

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!

Issues with matplotlib attribute errors

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()

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")

Categories

Resources