0

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

1
  • I think you would want to provide a minimal reproducible example here, such that people can reproduce the issue and provide a solution based on that. Commented Nov 16, 2018 at 23:30

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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)

1 Comment

Thank you very much this sorted out my problem. Would you know how to increase the figure size in ax graphs?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.