Seaborn Plot is not displaying - python

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!

Related

Figure not displayed with matplotlib.use('Agg')

I work with matplotlib. When I add the following lines, the figure is not displayed.
import matplotlib
matplotlib.use('Agg')
here is my code :
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plot
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
fig = plot.figure(figsize=(12,9))
def convert_sin_cos(x):
fft_axes = fig.add_subplot(331)
y = np.cos(x)
fft_axes.plot(x,y,'g*')
for i in range(3):
fft_axes = fig.add_subplot(332)
x=np.linspace(0,10,100)
fft_axes.plot(x,i*np.sin(x),'r+')
plot.pause(0.1)
convert_sin_cos(x)
Thanks
That's the idea!
When I run your code, the console says:
matplotlibAgg.py:15: UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure.
How can it be useful? When you're running matplotlib code in a terminal with no windowing system, for example: a cluster (running the same code with different inputs, getting lot of results and without the need to move the data I can plot whatever I need).

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

plt.show() not executing properly

Currently, I am attempting to follow along with a Sentdex YouTube tutorial video (https://www.youtube.com/watchv=cExOVprMlQg&list=PLQVvvaa0QuDe6ZBtkCNWNUbdaBo2vA4RO), however I am running into some difficulties with plt.show(). I have written this script nearly verbatim as detailed in this video and I have turned to StackOverflow to update any syntax, yet I have not been able to actually view this graph. Nothing comes up when I run the script, the shell just spits out '>>'. I have changed backends, unistalled, upgraded and reinstalled matplotlib. I've also tried this script on the exact version of Python seen in this video as well as 3.6.1 and a few others on OS X and Windows 10 via Parallels - still running into the same issue.
Here is my code thus far:
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.ticker as mticker
import matplotlib.dates as mdates
import numpy as np
import pylab
def graphRawFX():
date, bid, ask = np.loadtext('GBPUSD1d.txt', unpack=True,
delimiter='-',
converters={0: mdates.strpdate2numb('%Y%m%d%H%M%S')})
fig = plt.figure(figsize=(10,7))
ax1 = plt.subplot2grid((40,40), (0), rowspan=40, colspan=40)
ax1.plot(date, bid)
ax1.plot(date, ask)
ax1.xaxis.set_major_formatter(mdate.DateFormatter('%Y-%m-%d %H:#M:#S'))
for label in ax1.axis,get_xticklabels():
label.set_rotation(45)
ply.gca().get_yaxis().get_major_formatter().set_useOffset(False)
plt.grid(True)
plt.show()
pylab.show()
Any thoughts on a solution?
You defined a function, which plots. But you never call the function! Your script is empty from python's perspective.
Add graphRawFX() at the end, without any indentation to actually call the function.
If this code is by any means incomplete and not your issue, check your install and clean up the code. The whole import pylab thing looks unwanted. Also ply does not exist and so on. Start with the basics, the official examples and the docs, not with some yt-video which uses tons of (advanced) stuff.
I have it working (mac OS). Just try to copy paste to see if there's some typing problem. (it was working without "import pylab" and the "pylab.show()" I have just put it to have the same code you have.
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.ticker as mticher
import matplotlib.dates as mdates
import numpy as np
import pylab
def graphRawFX():
date,bid,ask = np.loadtxt('GBPUSD1d.txt', unpack=True, delimiter=',',converters={0:mdates.strpdate2num('%Y%m%d%H%M%S')})
fig = plt.figure(figsize=(10,7))
ax1 = plt.subplot2grid((40,40), (0,0), rowspan=40, colspan=40)
ax1.plot(date,bid)
ax1.plot(date,ask)
plt.gca().get_yaxis().get_major_formatter().set_useOffset(False)
ax1.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d %H:%M:%S'))
for label in ax1.xaxis.get_ticklabels() :
label.set_rotation(45)
ax1_2=ax1.twinx()
ax1_2.fill_between(date,0, (ask-bid),facecolor='g',alpha=.3)
plt.subplots_adjust(bottom=.23)
plt.grid(True)
plt.show()
pylab.show()
graphRawFX()

Seaborn displays different color for different run

I followed the setting from here to make matplotlib/seaborn available to display in Zeppelin. However, with the following code:
%python
import seaborn as sns
import matplotlib
import numpy as np
matplotlib.use('Agg')
import matplotlib.pyplot as plt
plt.rcdefaults()
import StringIO
def show(p):
img = StringIO.StringIO()
p.savefig(img, format='svg')
img.seek(0)
print "%html <div style='width:600px'>" + img.buf + "</div>"
""" Prepare your plot here ... """
# Use the custom show function instead of plt.show()
x = np.random.randn(100)
ax = sns.distplot(x)
show(sns.plt)
It is strange that the displayed figure show the desired lightblue color the first time I run the code but will display different colors if I execute the same piece of code. Is there a way to force seaborn to keep constant color being displayed? Thanks.
It's not entirely clear what is meant by "running a second time".
However you may try to actually close the figure before running it again. E.g.
plt.close("all")
in order to make sure, a new figure is created which should have the same default color every time.

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

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)

Categories

Resources