共用y轴的双图形绘制

本文介绍如何使用matplotlib和pandas库来绘制复杂的混合图表,包括堆叠条形图、普通条形图和折线图在同一张图表上的实现方法,并提供具体的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

实现这种形式的图形,可通过matplotlib和pandas的实现,相比下pandas实现方便的多。

我数据分析的时候主要是stacked bar、bar和line形式的放在一张图上。stacked bar若用matplotlib实现的话会比较复杂(多组)

 

先上图吧

 

def plot_stacked_bar(left_data, right_data):
    width = .3
    axe = plt.subplot(111)
    axe = left_data.plot(kind='bar', stacked=True, ax=axe, width=width, use_index=True, legend=False)
    axe.set_xticklabels(left_data.index, rotation=0)

    #add patches to the stacked bar
    patterns = ('-', '+', 'x', '\\', '*', 'o', 'O', '.', '/')
    bars = axe.patches
    hatches = ''.join(h*len(left_data) for h in patterns)
    for bar, hatch in zip(bars, hatches):
        bar.set_hatch(hatch)
    
    #plottint the line sharing the same x-axis on the secondary y-axis
    axf = axe.twinx()
    axf.plot(axe.get_xticks(), right_data, linestyle='-', marker='o', linewidth=2.0)
    axf.set_ylim((0, 90))

另一种形式的图形:

 

from matplotlib import pyplot as plt
import pandas as pd
from pandas import Series
import numpy as np
n = 50
x = pd.period_range('2001-01-01', periods=n, freq='M')
y1 = (Series(np.random.randn(n)) + 5).tolist()
y2 = (Series(np.random.randn(n))).tolist()
df = pd.DataFrame({'bar':y2, 'line':y1}, index=x)

# let's plot
plt.figure(figsize=(20, 4))
ax1 = df['bar'].plot(kind='bar', label='bar')
ax2 = ax1.twiny()
df['line'].plot(kind='line', label='line', ax=ax2)
ax2.grid(color="red", axis="x")

def align_xaxis(ax2, ax1, x1, x2):
    "maps xlim of ax2 to x1 and x2 in ax1"
    (x1, _), (x2, _) = ax2.transData.inverted().transform(ax1.transData.transform([[x1, 0], [x2, 0]]))
    xs, xe = ax2.get_xlim()
    k, b = np.polyfit([x1, x2], [xs, xe], 1)
    ax2.set_xlim(xs*k+b, xe*k+b)

align_xaxis(ax2, ax1, 0, n-1)

 

#参考#

 

转载于:https://www.cnblogs.com/nju2014/p/5049208.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值