Ryan E
Ryan E

Reputation: 3

Pandas Graph Bar and Line plot problems

I am Trying to plot a line graph on top of a bar plot for analysis from a dataframe. Every time i try and add the line graph, the y axis on the right goes haywire and the bar plot headers on the x axis change from being correct to alphabetical for some reason. I would like the y-axis on the right to be in order and the line to be straightened out if possible, Below is the bar plot after the line is added I am trying to plot the index value on the x which is the town labels, Town/city on the left y-axis, and population on the right axis.

It should be belfast first, then Londonderry.

enter image description here

Appreciate it if someone could help.

x1= CitySample2017["index"]
y1= CitySample2017["Town/City"]



y2= CitySample2017["Population"]

ax1= CitySample2017.plot.bar(y="Town/City", x='index')

ax2 = ax1.twinx()

ax2.plot(x1, y2)

https://i.sstatic.net/ZlI2I.jpg

Upvotes: 0

Views: 1981

Answers (2)

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339220

You are using matplotlib 2.1. Upgrade to matplotlib 2.2 or higher and the code will work as expected.

import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame({"index" : ["Belfast", "London", "Twoabbey", "Lisboa", "Barra"],
                   "town" : [5000,1000,600,600,500],
                   "pop" : [12,14,16,18,20]})

ax1= df.plot.bar(y="town", x='index')

ax2 = ax1.twinx()

ax2.plot(df["index"], df["pop"])

plt.show()

enter image description here

Upvotes: 1

Peter Leimbigler
Peter Leimbigler

Reputation: 11105

I can't be sure without seeing your data, but try running this instead of your code:

ax1 = CitySample2017.plot.bar(x='index', y='Town/City')
ax2 = ax1.twinx()
CitySample2017.plot(x='index', y='Population', ax=ax2)

Upvotes: 0

Related Questions