Why the scatter plot is not showing inside pairplot - python-3.x

sns.pairplot(advertising, x_vars=['TV', 'Newspaper', 'Radio'], y_vars='Sales',size=4, aspect=1, kind='scatter')
plt.show()
here when i am calling the pairplot function it is not showing the first plot, if you change the sequence of x_vars then again it wont show the first plot.
But you can see it individually, How can i see all of them in a single pairplot.

This is a bug/feature introduced in seaborn v.0.11.0.
The workaround it to pass diag_kind=None to pairplot

Related

Where/When the interpreter generates the graphic output, seaborn vs matplotlib

My question is about using seaborn and matplotlib together, common practice in many works.
I don't understand what command actually generates the graphic output...
How does the Python interpreter know when to plot the graph?
I used to think sns was drawing the graph, since it would be the last command before a graphic output:
plt.title("Monthly Visitors to Avila Adobe")
plt.xlabel("Date")
sns.lineplot(data=museum_data['Avila Adobe'],label='Avila Adobe')
But I found others examples with inverted calls, plt in last, and the graphic output displayed only after the plt call:
sns.lineplot(data=museum_data['Avila Adobe'],label='Avila Adobe')
plt.title("Monthly Visitors to Avila Adobe")
plt.xlabel("Date")
The two codes above do exact the same graphics.
I understand seaborn is build on top of matplotlib.
But,
I don't understand where/when the code generates the graphic output: after the sns or after the plt?
What statement draw the graph?
If my rationalization is wrong, pls clarify why.
Seaborn and Matplotlib are two of Python's most powerful visualization libraries. Seaborn uses fewer syntax and has stunning default themes and Matplotlib is more easily customizable through accessing the classes.
Seaborn
The seaborn package was developed based on the Matplotlib library. It is used to create more attractive and informative statistical graphics. While seaborn is a different package, it can also be used to develop the attractiveness of matplotlib graphics.
To answer your question, When we load seaborn into the session, everytime a matplotlib plot is executed, seaborn's default customizations are added. However, a huge problem that troubles many users is that the titles can overlap. Combine this with matplotlib's only confusing naming convention for its titles it becomes a nuisance. Nevertheless, the attractive visuals still make it usable for every Data Scientist's work.
In order to get the titles in the fashion that we want and have more customizability, We need to use the seaborn & matplotlib structure . Note that this is only necessary if we use subtitles in our plots. Sometimes they are necessary so it is better to have it on hand. Refer below code for more details.
matplotlib style plot :
import matplotlib.pyplot as plt
import numpy as np
# using some dummy data for this example
xs = np.random.randint( 0, 10, size=10)
ys = np.random.randint(-5, 5, size=10)
# plot the points
fig = plt.figure(figsize=(12,6))
fig.suptitle('Matplotlib with Python', fontsize='x-large', fontweight='bold')
plt.subplot(121)
plt.scatter(xs,ys,c='b') # scatter graph plotted from this line
plt.grid()
plt.subplot(122)
plt.plot(xs,ys,'bo--') # line graph plotted from this line
plt.grid()
Seaborn style plot :
import seaborn as sns
sns.set()
fig = plt.figure()
fig.suptitle('Seaborn with Python', fontsize='x-large', fontweight='bold')
fig.subplots_adjust(top=0.87)
#This is used for the main title. 'figure()' is a class that provides all the plotting elements of a diagram.
#This must be used first or else the title will not show.fig.subplots_adjust(top=0.85) solves our overlapping title problem.
fig = plt.figure(figsize=(12,6))
ax = fig.add_subplot(121)
fontdict={'fontsize': 14,
'fontweight' : 'book',
'verticalalignment': 'baseline',
'horizontalalignment': 'center'}
ax.set_title('Scatter Plot Tutorial', fontdict=fontdict)
#This specifies which plot to add the customizations. fig.add_sublpot(121) corresponds to top left plot no.1
plt.plot(xs, ys, 'bo' ) # scatter graph plotted from this line in seaborn with matplotlib command & seaborn style
plt.xlabel('x-axis', fontsize=14)
plt.ylabel('yaxis', fontsize=14)
ax = fig.add_subplot(122)
fontdict={'fontsize': 14,
'fontweight' : 'book',
'verticalalignment': 'baseline',
'horizontalalignment': 'center'}
ax.set_title('Line Plot Tutorial', fontdict=fontdict)
sns.lineplot(xs, ys) # line graph plotted from this line in seaborn with seaborn command & seaborn style
plt.xlabel('x-axis', fontsize=14)
plt.ylabel('yaxis', fontsize=14);
Now compare both plots stylewise and please read code comments carefully.
source
Python seaborn tutorial
I posted this question 6 months ago, so, now I'm 6 months more experienced!
How does the Python interpreter know when to plot the graph?
I don't understand where/when the code generates the graphic output: after the sns or after the plt?
What I learn:
Well, I was used to a approach where after a given command and I get a response.
But that is no the case when working with graphics in Python, specially when using a notebook...
Actually, using matplotlib, sns, etc, we can, in a cumulative way, prepare many aspects before actually output the graphic.
And many commands (functions, methods) are capable to do the real display, but it is the last "complete" command (my interpretation here) does the job.
So, since they are consistent, the order is not a problem.
Sure, we need to assure the good logic!
It was that I would like to understand.
The #jay-patel answer helped me to think about it, he give me good examples.

Is it possible to update inline plots in Python (Spyder)?

Setup: Anaconda 3 (Win10 64), Spyder 4 and Python 3.7. The IPython Graphics setting is default (Inline).I'm still a new to Python but I've looked around and have not found an answer that solves my problem so far. Thanks everyone in advance.
So in this setup, whenever I create a plot using matplotlib, it appears in the plot pane of Spyder. e.g.
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
df = pd.DataFrame(np.random.randint(0,100,size=(100, 1)), columns=list('A'))
bp = df.boxplot(column = 'A')
creates a boxplot. Now, if I want to add a title to the plot, the code would be
bp.set_title("This Title")
This is where I'm getting some problems. If I run the entire block together
df = pd.DataFrame(np.random.randint(0,100,size=(100, 1)), columns=list('A'))
bp = df.boxplot(column = 'A')
bp.set_title("This Title")
then I get a box plot with "This Title" as the title, showing up in the plot pane,
which is what I want.
However, if I run the above code line by line in the IPython console, the 2nd line will produce a boxplot as expected, but the 3rd line will not have an effect on the image in the plot pane, so the image in the plot pane still do not have a title
Now,if i go to Tools > Preference >IPython Console > Graphics and set the graphics backend to Automatic instead of the default Inline, then when I run the code in the Console line by line, I get an image that pops up in another window, and that it does update/refreshes based on new lines entered into the console. I understand that the inline plots are supposed to be static, but I thought I saw another post where someone said that it is possible to update inline plots? So now my questions are:
Do plots only update/refresh by line codes in the IPython console if the Graphics Backend is not static like inline?
Why do I get different result when I run code blocks vs line by line?
If it is possible to update the inline plots (preferably in the plot pane of Spyder), how do you do it? I've tried various methods to redraw the plots,for example
plt.show()
plt.draw()
bp.get_figure().canvas.draw()
but none of these updates the image in the plot pane. I figured that even if I can't update the image, I should at least be able to redraw it (i.e a 2nd image appears in the plot pane with the update characteristics). But nothing I've tried worked so far. Please advise and thanks again.
(Spyder maintainer here) About your questions:
Do plots only update/refresh by line codes in the IPython console if the Graphics Backend is not static like inline?
Correct.
Why do I get different result when I run code blocks vs line by line?
Because when you run code cells (which is what I think you mean by "code blocks") your plot is shown at the end of that code and hence it takes all modifications you've done to it in intermediate lines.
If it is possible to update the inline plots (preferably in the plot pane of Spyder), how do you do it?
No, it's not possible. As you correctly mentioned above, inline plots are static images, so they can't be modified.

How to draw a coordinate map containing both horizontal and vertical boxplot with matplotlib

I want to draw a picture like this using matplotlib.
How to do that?
Thank you in advance.
Example/i.stack.imgur.com/Vk57A.png
seaborn.jointplot might be what you're looking for. Specify to draw boxplots in the marginal plot and a regplot in the "main plot".
Seaborn builds on top of matplotlib, so you can still modify linecolors, markercolors etc. and draw annotations with plt.annotate.

"pixel dimension information" when plotting with image in gnuplot

Using gnuplot v5 patch 6 on windows 10 (wxt terminal)
I have a data file of 2D vectors arranged in six columns (x, y, v_x, v_y, v_mag, rho) that I'm trying to plot as a heatmap of v_mag against x and y. The plot generates fine, but it's always coming up with
"No dimension information for 80000 pixels total. Try 200 x 400"
But I have no idea where to specify this in the terminal.
I realise that I can use pm3d map for this, but this doesn't work without setting dgrid3d and that causes problems with plotting dots on top of the heatmap which I'm also doing. I also don't want to generate a matrix file just for the image plot since I need the vector data for analysis later.
In terms of an example, the plot will generate if I literally just write:
plot 'vectors.dat' using 1:2:5 with image, 'dots.dat' with dots
EDIT: added 'set pm3d' to example code
EDIT: example is now minimal code to produce desired plot
EDIT: example data file can be found here
Any help would be appreciated.
After updating my gnuplot to v5.2, this problem has disappeared.

Matplotlib Crash When Figure 1 not Closed Last

I am plotting mutliple figures using Matplotlib using Python 3.4.
When the multiple figures are open and I close the windows closing the first figure last (ie once all other figures are closed) python does not crash.
If, however, I close the first figure that was plotted first and then close the rest Python crashes.
It seems as though you need to close the windows in such an order that the first window that was opened must be closed last. Has anyone else experienced and is there a solution?
Here is a trivial example code that can be used to verify:
import matplotlib.pyplot as plt
plt.figure(1) # the first figure
plt.plot([1,2,3])
plt.figure(2) # a second figure
plt.plot([4,5,6])
plt.show()
As discussed on the IPython bug tracker this is a bug in a TCL/TK library which is shipped with python 3.4 on windows.
Changing the backend to Qt works around the problem by using a different gui framework.
The way I have managed to solve this issue has been to use Qt4 as the matplotlib backend.
Simply add the following two lines of code after importing matplotlib.
import matplotlib as mpl
mpl.rcParams['backend'] = "qt4agg"
mpl.rcParams['backend.qt4'] = "PySide"
This is what I do on Python 3 and have no plot closing errors
I use this to do effectively what should be done by plt.close('all'):
def closeall(): # this closes all figures in reverse order
l = plt.get_fignums()
l.reverse()
for a in l:
plt.close(a)
Whenever you are plotting multiple figures, do not use plt.show, create your figures separately in a figure instance and add an Axes using add_subplot. Here is an example:
import matplotlib.pyplot as plt
fig1 = plt.figure()
ax1 = fig1.add_subplot(211) # the first subplot in the first figure
ax1.plot([1,2,3])
ax2 = fig1.add_subplot(212) # the second subplot in the first figure
ax2.plot([4,5,6])
plt.suptitle('Easy as 1,2,3')
fig1.show()
fig2 = plt.figure()
ax3 = fig2.add_subplot(211) # the first subplot in the second figure
ax3.plot([4,5,6])
ax4 = fig2.add_subplot(212) # the second subplot in the second figure
ax4.plot([4,5,6])
plt.suptitle('Easy as 1,2,3')
fig2.show()
By doing so you can still use your python shell even when the plots are active. This is the best way to plot multiple plots.

Resources