python pandas plot line chart in pandas.plot hbar - pandas

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

Related

Line plot is filled in Pandas and Matplotlib

I am using pandas and matplotlib to plot a data set.
I am trying to plot two values in a DataFrame a a line plot, but The plot is displaying filled.
but I want this:
my code:
%matplotlib inline
from matplotlib import style
import pandas as pd
from matplotlib import pyplot as plt
covid = pd.read_csv('covid_19_india.csv')
#covid.head()
plt.style.use('Solarize_Light2')
plt.plot(covid.Date, covid.Deaths)
Help needed from community!

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 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'])

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

Creating a bar plot using Seaborn

I am trying to plot bar chart using seaborn. Sample data:
x=[1,1000,1001]
y=[200,300,400]
cat=['first','second','third']
df = pd.DataFrame(dict(x=x, y=y,cat=cat))
When I use:
sns.factorplot("x","y", data=df,kind="bar",palette="Blues",size=6,aspect=2,legend_out=False);
The figure produced is
When I add the legend
sns.factorplot("x","y", data=df,hue="cat",kind="bar",palette="Blues",size=6,aspect=2,legend_out=False);
The resulting figure looks like this
As you can see, the bar is shifted from the value. I don't know how to get the same layout as I had in the first figure and add the legend.
I am not necessarily tied to seaborn, I like the color palette, but any other approach is fine with me. The only requirement is that the figure looks like the first one and has the legend.
It looks like this issue arises here - from the docs searborn.factorplot
hue : string, optional
Variable name in data for splitting the plot by color. In the case of ``kind=”bar”, this also influences the placement on the x axis.
So, since seaborn uses matplotlib, you can do it like this:
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
x=[1,1000,1001]
y=[200,300,400]
sns.set_context(rc={"figure.figsize": (8, 4)})
nd = np.arange(3)
width=0.8
plt.xticks(nd+width/2., ('1','1000','1001'))
plt.xlim(-0.15,3)
fig = plt.bar(nd, y, color=sns.color_palette("Blues",3))
plt.legend(fig, ['First','Second','Third'], loc = "upper left", title = "cat")
plt.show()
Added #mwaskom's method to get the three sns colors.