Seaborn plot is not showing [duplicate] - python

This question already has answers here:
Seaborn plots not showing up
(8 answers)
Closed 7 years ago.
I'm following the tutorial here for what seems like the simplest example - a linear relationship.
I'm unclear on the very permissive imports, and don't seem to be able to show my plot.
my_seaborn_test.py:
import numpy as np
import seaborn as sns
class SeabornTest(object):
def run_example(self):
sns.set(color_codes=True)
np.random.seed(sum(map(ord, "regression")))
tips = sns.load_dataset("tips")
sns.lmplot(x="size", y="tip", data=tips, x_estimator=np.mean)
On the command line:
python
from my_seaborn_test import SeabornTest
st = SeabornTest()
st.run_example()
All I get is silence and this warning:
/home/me/anaconda3/envs/myenv/lib/python3.5/site-packages/matplotlib/__init__.py:892: UserWarning: axes.color_cycle is deprecated and replaced with axes.prop_cycle; please use the latter.
warnings.warn(self.msg_depr % (key, alt_key))

As mentioned above in the other answer, running in IPython will allow you to see it, but that isn't the only way.
The last line of your method returns a FacetGrid object, which is silently discarded after your method exits, which is why you are seeing nothing other than the warning which is produced. You will need to do something with this object (IPython automatically "prints" it when it is produced).
Change your method like so:
def run_example(self):
sns.set(color_codes=True)
np.random.seed(sum(map(ord, "regression")))
tips = sns.load_dataset("tips")
sns.lmplot(x="size", y="tip", data=tips, x_estimator=np.mean).fig.show()
Now your example will open a graphical window showing the figure
If you want to save it instead, change that last line to
sns.lmplot(x="size", y="tip", data=tips, x_estimator=np.mean).savefig("testing.png")
This sort of behavior is typical of matplotlib and thus seaborn which is built on top of matplotlib. You will have to specify what needs to be done with graphics objects (the %matplotlib inline call in IPython is actually telling IPython to catch these objects and display them).

Related

When I run '''sns.histplot(df['price'])''' in pycharm I get the code output but no graph, why is this?

I'm using pycharm to run some code using Seaborn. I'm very new to python and am just trying to learn the ropes so I'm following a tutorial online. I've imported the necessary libraries and have run the below code
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
# import the data saved as a csv
df = pd.read_csv('summer-products-with-rating-and-performance_2020-08.csv')
df["has_urgency_banner"] = df["has_urgency_banner"].fillna(0)
df["discount"] = (df["retail_price"] -
df["price"])/df["retail_price"]
df["rating_five_percent"] = df["rating_five_count"]/df["rating_count"]
df["rating_four_percent"] = df["rating_four_count"]/df["rating_count"]
df["rating_three_percent"] = df["rating_three_count"]/df["rating_count"]
df["rating_two_percent"] = df["rating_two_count"]/df["rating_count"]
df["rating_one_percent"] = df["rating_one_count"]/df["rating_count"]
ratings = [
"rating_five_percent",
"rating_four_percent",
"rating_three_percent",
"rating_two_percent",
"rating_one_percent"
]
for rating in ratings:
df[rating] = df[rating].apply(lambda x: x if x>= 0 and x<= 1 else 0)
# Distribution plot on price
sns.histplot(df['price'])
My output is as follows:
Process finished with exit code 0
so I know there are no errors in the code but I don't see any graphs anywhere as I'm supposed to.
Ive found a way around this by using this at the end
plt.show()
which opens a new tab and uses matplotlib to show me a similar graph.
However in the code I'm using to follow along, matplotlib is not imported or used (I understand that seaborn has built in Matplotlib functionality) as in the plt.show statement is not used but the a visual graph is still achieved.
I've also used print which gives me the following
AxesSubplot(0.125,0.11;0.775x0.77)
Last point to mention is that the code im following along with uses the following
import seaborn as sns
# Distribution plot on price
sns.distplot(df['price'])
but distplot has now depreciated and I've now used histplot because I think that's the best alternative vs using displot, If that's incorrect please let me know.
I feel there is a simple solution as to why I'm not seeing a graph but I'm not sure if it's to do with pycharm or due to something within the code.
matplotlib is a dependency of seaborn. As such, importing matplotlib with import matplotlib.pyplot as plt and calling plt.show() does not add any overhead to your code.
While it is annoying that there is no sns.plt.show() at this time (see this similar question for discussion), I think this is the simplest solution to force plots to show when using PyCharm Community.
Importing matplotlib in this way will not affect how your exercises run as long as you use a namespace like plt.
Be aware the 'data' must be pandas DataFrame object, not: <class 'pandas.core.series.Series'>
I using this, work finely:
# Distribution plot on price
sns.histplot(df[['price']])
plt.show()

How to use matplotlib to plot pyspark sql results using shell

I know the question has been asked before regarding using matplotlib in pyspark. I wanted to know how to do the same through shell. I used the same code as given in this solution
How to use matplotlib to plot pyspark sql results
However I am getting this when I run in the shell.
<matplotlib.axes.AxesSubplot object at 0x7f1cd604b690>
I am not entirely sure I do understand your question, so please provide more details in case I got you wrong.
If you happen to see an instance of a Subplot-Class such as given by you, rather have the previous command's return value assigned to a variable, because otherwise you cannot use it. I will give a simple example of a subplot below:
In essence, instead of:
import matplotlib.pyplot as plt
fig = plt.figure()
fig.add_subplot(111)
do the following:
import matplotlib.pyplot as plt
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax1.plot(x_values, y_values)
plt.show()
If this didnt answer your question, please provide a minimal working example of what you are doing.

Jupyter Notebook _repr_png_ returning Matplotlib plot

My current project requires a lot of evaluation. For convenience, I wrote a data class with Jupyter Notebook representations. My intention was to output different indicators as text (for copy & paste) and a boxplot as it is more descriptive in some cases.
To my surprise, (only) not calling show() or close() worked. However, this feels hacky to me. Thus my question: Is this behaviour intended? And why does it work?
To clarify what I'm wondering about, I expected this to happen regardless of calling show() or not:
I know, I could simply add a plot method to the data class and call that, but this really interests me.
Simplified version of the code:
class EvaluationResult:
def __init__(self, indicators, errors):
self.indicators = indicators
self.errors = errors
def _repr_html_(self):
return f"""
<b>Indicator A:</b> {self.indicators[1]:.3f}<br>
<b>Indicator B:</b> {self.indicators[2]:.3f}"""
def _repr_png_(self):
fig = plt.figure(figsize=(8, 2))
plt.boxplot(self.errors, whis=[5, 95],
showfliers=False, vert=False)
plt.title('Error distribution')
plt.tight_layout()
# return fig -- returning the figure is not mandatory
Versions: Python v3.6.4 | Jupyter Notebook v5.4.1 | IPython v6.2.1 | Matplotlib v2.2.2
Just to clarify something first - The plot was not generated because you returned a figure, but because you called the plt.boxplot() method. Simply running the following line in its own cell will auto-generate the plot inline without a call to plt.show()
plt.boxplot(errors, whis=[5, 95], showfliers=False, vert=False)
Here is a similar question which basically states that this is the default behavior.
I've always included the line %matplotlib inline in my notebook near the imports not knowing that it was the default behavior. I believe changing that line to %matplotlib notebook will change this behavior and force you to call plt.show() and plt.figure() when needed.

backend_qt5.py "'figure' is an unknown keyword argument, In matplotlib

I am trying to run a simple code to plot my data using matplotlib in python2.7.10 :
import matplotlib.pyplot as plt
y=[23,35,43,54,76]
x=[2,4,5,6,7]
plt.plot(y,x)
I am getting the error:
super(FigureCanvasQTAggBase, self).__init__(figure=figure)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/backends/backend_qt5.py", line 239, in __init__
super(FigureCanvasQT, self).__init__(figure=figure)
TypeError: 'figure' is an unknown keyword argument
How can I fix it?
This seems to be a duplicate of: matplotlib Qt5Agg backend error: 'figure' is an unknown keyword argument, which I just posted an answer for, and duplicated below:
I had the same issue. I found the solution here
Specifically, the following now works:
import matplotlib
matplotlib.use('Qt4Agg')
from matplotlib import pyplot as plt
plt.figure(figsize=(12,8))
plt.title("Score")
plt.show()
Just adding to Marc's answer. If you are using Spyder,
matplotlib.use('Qt4Agg')
may not work well because matplotlib has been imported when you open Spyder.
Instead you can go to (in Spyder) Tools - Preferences -IPython console - Graphics to change the backend and restart Spyder.
adding to this, i ran into this problem when i wanted to plot my values for my KNN training sets and test set results.
using TkAgg also fixes the problem
"matplotlib.use('TkAgg')"
import matplotlib
matplotlib.use('TkAgg')
#matplotlib.use('Qt4Agg')
import matplotlib.pyplot as plt
plt.figure(figsize=(12,8))
plt.title("Score")
plt.show()

ipython pandas plot does not show

I am using the anaconda distribution of ipython/Qt console. I want to plot things inline so I type the following from the ipython console:
%pylab inline
Next I type the tutorial at (http://pandas.pydata.org/pandas-docs/dev/visualization.html) into ipython...
import matplotlib.pyplot as plt
import pandas as pd
ts = pd.Series(randn(1000), index = pd.date_range('1/1/2000', periods=1000))
ts = ts.cumsum()
ts.plot()
... and this is all that i get back:
<matplotlib.axes.AxesSubplot at 0x109253410>
But there is no plot. What could be wrong? Is there another command that I need to supply? The tutorial suggests that that is all that I need to type.
Plots are not displayed until you run
plt.show()
There could be 2 ways to approach this problem:
1) Either invoke the inline/osx/qt/gtk/gtk3/tk backend. Depends on the ipython console that you have been using. So, simply do:
%matplotlib inline #Here the inline backend is invoked, which removes the necessity of calling show after each plot.
or for ipython/qt console, do:
%matplotlib qt #This one works for me, thus, depends on the ipython console you use.
#
2) Or, do the traditional way as aforementioned (already answered above on this page):
plt.show() #However, you will have to call this show function each time.

Categories