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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 01:29:47  来源:igfitidea点击:

Barplot/line plot on same plot, but different axis and line plot in front of barplot

pythonpandasmatplotlib

提问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.

一切都很好。

GoodGraph

好图

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

SadGraph

悲伤图

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)

enter image description here

在此处输入图片说明

Or, create two axes ax1and ax2with twinx().

或者,创建两个轴ax1ax2使用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()

enter image description here

在此处输入图片说明