同一图中的条形图和计数图

问题描述 投票:1回答:1

我想在同一图中绘制条形图并计数图。但是,当我用两个不同的y轴绘制它们时,两个图相互重叠(参见图片)。是否可以将其中一个地块“移”到一边?

fig, ax1 = plt.subplots(figsize=(15, 10))
ax2 = ax1.twinx()

ax1.bar(x=damage_sum[Kanton], height=damage_sum[sTot], color=colors)
ax2 = sns.countplot(x=dff[Kanton], data=dff, palette=colors, order=cantons) 

数据描述

damage_sum[Kanton] = ['ZG', 'VD', 'SO', 'SG', 'NW', 'NE', 'LU', 
                      'JU', 'GR', 'GL', 'FR', 'BL', 'AG']

enter image description here

python matplotlib count bar-chart
1个回答
1
投票

虽然有些混乱,但是手动更改条的宽度和位置可以完成工作。我使用了seaborn的barplot,绘制数据帧更容易

import seaborn as sns;sns.set()
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

def change_width(ax, new_value,recenter=False) :
    for patch in ax.patches :
        current_width = patch.get_width()
        diff = current_width - new_value
        patch.set_width(new_value)
        if recenter==True:  
            patch.set_x(patch.get_x() + diff * .5) #To recenter the bars

df = sns.load_dataset('tips')
fig, ax1 = plt.subplots(figsize=(8, 8))
ax2 = ax1.twinx()

ax1 = sns.countplot(x='day', data=df)
change_width(ax1, 0.35)

ax2 = sns.barplot(x="day", y="total_bill", data=df,palette='viridis')
change_width(ax1, 0.35,True)

enter image description herebarplot的条形图和countplot的条形图在高度上的变化很大,因此我想说归一化值,countplot不支持Estimator,因此请使用barplot的estimator查找相对值

estimator=lambda x: len(x) / len(df) * 100

change_width功能

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