Pandas Graph Bar和Line情节问题

问题描述 投票:0回答:2

我试图在条形图上绘制折线图,​​以便从数据框中进行分析。每次我尝试添加折线图时,右边的y轴都会变得混乱,x轴上的条形图标题由于某种原因从正确变为字母。我希望右边的y轴是有序的,如果可能的话,直线将被拉直,下面是添加线后的条形图我试图在x上绘制索引值,即城镇标签,左侧y轴上的城镇/城市,右轴上的人口。

首先应该是贝尔法斯特,然后是伦敦德里。

enter image description here

如果有人可以提供帮助,请欣赏它。

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

python pandas matplotlib bar-chart line-plot
2个回答
0
投票

我无法确定没有看到您的数据,但尝试运行此代码而不是代码:

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

1
投票

您正在使用matplotlib 2.1。升级到matplotlib 2.2或更高版本,代码将按预期工作。

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

© www.soinside.com 2019 - 2024. All rights reserved.