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

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

Related

How to plot (correctly) lineplot from pandas dataframe?

I'm plotting a lineplot from a pandas dataframe. However the labels are overlapped on the right side of the X axis instead of to the relative point mark on the line. What is missing?
Here the full code and the pic
#importing pandas package
import pandas as pd
import matplotlib.pyplot as plt
import csv
import seaborn as sns
# making data frame from csv file
dataset = pd.read_csv('curve.csv.csv')
df = pd.DataFrame(dataset.sort_values('Split')[['Split', 'Score']])
df.reset_index(drop=True, inplace=True)
print(df)
ax = df.plot.line(x='Split',y='Score',color='green',marker=".")
ax.set_xlim((0, 1))
ax.grid(True)
# set the tick marks for x axis
ax.set_xticks(df.Score)
ax.set_xticklabels(['.005','.010','.015','.020','.040','.060','.080','1','15','20','25','30','35','40','45','50','55','60'
,'65','70','75','80','85','90','95'])
ax.grid(True, linestyle='-.')
ax.tick_params(labelcolor='r', labelsize='medium', width=3)
plt.show()
My desired output would be to have all the labels on the X axis aligned to the relative marker point on the line.
You seem to be using the y-values (df.Score) as the positions of your x-ticks.
I assume you meant
ax.set_xticks(df['Split'])

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

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.

python pandas plot line chart in pandas.plot hbar

I have a horizontal bar chart created with
df.plot(kind='barh', ax=ax)
and now I would like to plot a horizontal line chart in the same axis. How can I do that. There seems to be no equivalent lineh
I tried to just flip axes when plotting a regular line
df=pd.DataFrame(dict(k=['A','B','C','D'], v=[1,3,2,3]))
df.plot(x='v', y='k')
but then pandas complains that there is no numerical data to plot
If you want to use matplotlib, you can do like the following. Here the command xticks() is to set x-tick labels only at integer values.
import pandas as pd
import matplotlib.pyplot as plt
df=pd.DataFrame(dict(k=['A','B','C','D'], v=[1,3,2,3]))
plt.plot(df.v, df.k)
plt.xticks(range(1, max(df.v)+1))
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()

Seaborn FacetGrid plots are empty if any of the sub-plots have no data

I have a dataset that I want to plot with FacetGrids using the seaborn library. The problem is my data is "sparse"; some of the individual subplots don't exist (ie. there are zero data points). I would like those cells to either not show up, or just show up and be blank, but still see the subplots that have data. Here's a simple example:
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
df = pd.DataFrame(columns=['a','b','c','d'],
data=[[1,1,1,4],[1,2,2,8],[2,1,2,12],[2,1,3,14]])
print df
g = sns.FacetGrid(df, col='a', row='b', hue='c')
g.map(plt.scatter, 'c', 'd', marker='o')
Unfortunately, when I plot this, I just get four empty plots instead of 3 filled plots and one empty one. If I change the last row of data to [2,2,3,14] instead, then all four plots appear as expected. Is this a bug in seaborn? Can I work around it somehow?