同一图上的条形图/折线图,但在条形图前的轴和折线图不同 [英] Barplot/line plot on same plot, but different axis and line plot in front of barplot

查看:179
本文介绍了同一图上的条形图/折线图,但在条形图前的轴和折线图不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用熊猫来绘制一些数据.

I'm using pandas to plot some data.

如果我画这个:

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

一切都很好.

如果将条形图轴绘制在辅助轴上,则条形图将位于折线图的前面,这样会妨碍查看线条.

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

  • 使用pandas/matplotlib
  • 条形图在辅助轴上,折线图在主轴上
  • 折线图位于条形图的前面

推荐答案

您可以将线放在主轴上.

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)

或者,使用 twinx() ax1和ax2 >.

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

这篇关于同一图上的条形图/折线图,但在条形图前的轴和折线图不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆