Why am I getting two plots (instead of one) in a Jupyter notebook? - pandas

When using %matplotlib notebook I'm getting two plots instead of one from a pandas Series.
Code in cell is:
%matplotlib notebook
import matplotlib.pyplot as plt
fig=plt.figure()
ax1=fig.add_subplot(1,1,1)
cTitle='H-alpha plot '+galaxy[10:17]
cXAxisTitle='Galactocentric radius/pixels'
cYAxisTitle='Data counts'
ax1.set_title(cTitle)
ax1.set_xlabel(cXAxisTitle)
ax1.set_ylabel(cYAxisTitle)
ax1.grid()
ds.plot()
I'm getting Fig 1 and Fig 2:
Title, axis labels and grid lines in Fig 1 are what I want (expect) and plot in Fig 2 is also what I expect. But why am I getting two plots anyway?

Start from:
%matplotlib inline
import matplotlib.pyplot as plt
once, at the beginning of your notebook.
My suggestion is to use inline instead of notebook.
Then run:
cTitle = 'H-alpha plot '+ galaxy[10:17]
cXAxisTitle = 'Galactocentric radius/pixels'
cYAxisTitle = 'Data counts'
ax1 = ds.plot(title=cTitle, grid=True)
ax1.set(xlabel=cXAxisTitle, ylabel=cYAxisTitle);
Note the semicolon at the end of the last instruction.
Otherwise you will have additional "messages" superimposed
on your drawing.

Related

Is there a way to draw shapes on a python pandas plot

I am creating shot plots for NHL games and I have succeeded in making the plot, but I would like to draw the lines that you see on a hockey rink on it. I basically just want to draw two circles and two lines on the plot like this.
Let me know if this is possible/how I could do it
Pandas plot is in fact matplotlib plot, you can assign it to variable and modify it according to your needs ( add horizontal and vertical lines or shapes, text, etc)
# plot your data, but instead diplaying it assing Figure and Axis to variables
fig, ax = df.plot()
ax.vlines(x, ymin, ymax, colors='k', linestyles='solid') # adjust to your needs
plt.show()
working code sample
import pandas as pd
import matplotlib.pyplot as plt
import seaborn
from matplotlib.patches import Circle
from matplotlib.collections import PatchCollection
df = seaborn.load_dataset('tips')
ax = df.plot.scatter(x='total_bill', y='tip')
ax.vlines(x=40, ymin=0, ymax=20, colors='red')
patches = [Circle((50,10), radius=3)]
collection = PatchCollection(patches, alpha=0.4)
ax.add_collection(collection)
plt.show()

how to prevent seaborn to skip year in xtick label in Timeseries Plot

I have included the screenshot of the plot. Is there a way to prevent seaborn from skipping the xtick labels in timeseries data.
Most seaborn functions return a matplotlib object, so you can control the number of major ticks displayed via matplotlib. By default, matplotlib will auto-scale, which is why it hides some year labels, you can try to set the MaxNLocator.
Consider the following example:
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
# load data
df = sns.load_dataset('flights')
df.drop_duplicates('year', inplace=True)
df.year = df.year.astype('str')
# plot
fig, ax = plt.subplots(figsize=(5, 2))
sns.lineplot(x='year', y='passengers', data=df, ax=ax)
ax.xaxis.set_major_locator(plt.MaxNLocator(5))
This gives you:
ax.xaxis.set_major_locator(plt.MaxNLocator(10))
will give you
Agree with answer of #steven, just want to say that methods for xticks like plt.xticks or ax.xaxis.set_ticks seem more natural to me. Full details can be found here.

matplotlib.plot in embedded IPython immediately shows plot with no chance for modifying the returned axes

Embed IPython in a script and run:
from IPython import embed
# code ...
embed()
%matplotlib
#^ With or without; same result
fig = plt.figure()
Can't do anything with fig at this point.
It's already shown and the window is displayed,
even though I never called show.
plt.show() # does absolutely nothing
I normally import matplotlib in IPython this way:
%matplotlib inline
import matplotlib.pyplot as plt
ax, fig = plt.subplots()
plt.plot([[1,1], [2,2]])
plt.show()
Does this help?

Empty Plots - matplotlib only shows frame of plot but no data

From my excel imported file, I want to plot specific entries i.e.rows and columns but plt.plot command does not display the data, only a blank frame is shown. please see the attached picture.
May be it has something to do with my code.
%matplotlib inline
import pandas as pd
import matplotlib.pyplot as plt
hpge = pd.read_excel('mypath\\filename.xlsx','Sheet3', skiprows=1,usecols='C:G,I,J')
x=[]
y=[]
x.append(hpge.E_KeV[2700:2900])# E_KeV is a column
y.append(hpge.Fcounts[2700:2900])# Fcounts is a column
x1=[]
y1=[]
x1.append(hpge.E[2700:2900])
y1.append(hpge.C[2700:2900])
#print(y1)
#print(x)
#plt.xlim(590,710)
#plt.yscale('log')
plt.plot(x, y, label='Cs')
plt.plot(x1,y1)
plt.show()

Stacking multiple plots on a 2Y axis

I am trying to plot multiple plots in a 2Y plot.
I have the following code:
Has a list of files to get some data;
Gets the x and y components of data to plot in y-axis 1 and y-axis 2;
Plots data.
When the loop iterates, it plots on different figures. I would like to get all the plots in the same figure.
Can anyone give me some help on this?
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
file=[list of paths]
for i in files:
# Loads Data from an excel file
data = pd.read_excel(files[i],sheet_name='Results',dtype=float)
# Gets x and y data from the loaded files
x=data.iloc[:,-3]
y1=data.iloc[:,-2]
y12=data.iloc[:,-1]
y2=data.iloc[:,3]
fig1=plt.figure()
ax1 = fig1.add_subplot(111)
ax1.set_xlabel=('x')
ax1.set_ylabel=('y')
ax1.plot(x,y1)
ax1.semilogy(x,y12)
ax2 = ax1.twinx() # instantiate a second axes that shares the same x-axis
ax2.plot(x,y2)
fig1.tight_layout()
plt.show()
You should instantiate the figure outside the loop, and then add the subplots while iterating. In this way you will have a single figure and all the plots inside it.
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
files=[list of paths]
fig1=plt.figure()
for i in files:
# Loads Data from an excel file
data = pd.read_excel(files[i],sheet_name='Results',dtype=float)
# Gets x and y data from the loaded files
x=data.iloc[:,-3]
y1=data.iloc[:,-2]
y12=data.iloc[:,-1]
y2=data.iloc[:,3]
ax1 = fig1.add_subplot(111)
ax1.set_xlabel=('x')
ax1.set_ylabel=('y')
ax1.plot(x,y1)
ax1.semilogy(x,y12)
ax2 = ax1.twinx() # instantiate a second axes that shares the same x-axis
ax2.plot(x,y2)
fig1.tight_layout()
plt.show()