简体   繁体   中英

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://imgur.com/a/z4oSjWS

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

在此处输入图片说明

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM