pandas 同一图上的条形图/线图,但条形图前面的轴和线图不同
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38131697/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Barplot/line plot on same plot, but different axis and line plot in front of barplot
提问by none
I'm using pandas to plot some data.
我正在使用Pandas来绘制一些数据。
If I plot this:
如果我绘制这个:
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame({'a': [100, 200, 150, 175],
'b': [430, 30, 20, 10]})
fig, ax1 = plt.subplots(figsize=(15, 10))
df['b'].plot(kind='bar', color='y')
df['a'].plot(kind='line', marker='d')
Everything plots fine.
一切都很好。
If I plot the bar axis on the secondary axis, the bar plot will be in front of the line plots, obstructing the lines from being viewed, like this.
如果我在辅助轴上绘制条形轴,条形图将位于线图的前面,阻碍线被查看,就像这样。
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame({'a': [100, 200, 150, 175],
'b': [430, 30, 20, 10]})
fig, ax1 = plt.subplots(figsize=(15, 10))
df['b'].plot(kind='bar', color='y', secondary_y=True)
df['a'].plot(kind='line', marker='d')
How do I make a bar plot/line plot where...
如何制作条形图/线图,其中...
- Using pandas/matplotlib
- Bar plot is on secondary axis and line chart is on primary axis
- Line plots are in front of the bar plot
- 使用Pandas/matplotlib
- 条形图在辅助轴上,折线图在主轴上
- 线图在条形图的前面
采纳答案by piRSquared
you could put line on primary axis.
你可以把线放在主轴上。
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame({'a': [100, 200, 150, 175],
'b': [430, 30, 20, 10]})
fig, ax1 = plt.subplots(figsize=(15, 10))
df['b'].plot(kind='bar', color='y')
df['a'].plot(kind='line', marker='d', secondary_y=True)
Or, create two axes ax1
and ax2
with twinx()
.
或者,创建两个轴ax1
并ax2
使用twinx()
.
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame({'a': [100, 200, 150, 175],
'b': [430, 30, 20, 10]})
fig, ax1 = plt.subplots(figsize=(15, 10))
ax2 = ax1.twinx()
df['b'].plot(kind='bar', color='y', ax=ax1)
df['a'].plot(kind='line', marker='d', ax=ax2)
ax1.yaxis.tick_right()
ax2.yaxis.tick_left()