Search code examples
pythonpandasmatplotlibbar-chartline-plot

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


Solution

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