gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 06:41:58 26 4
gpt4 key购买 nike

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

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

ax1.bar(x=score[team], height=score[tot], color=colors)
ax2 = sns.countplot(x=dff[team], data=dff, palette=colors, order=team)

数据描述

score[team] = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm']

enter image description here

最佳答案

虽然有点乱,但手动更改栏宽度和位置可以完成工作。
我使用了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 here条形图的条形图和计数图的条形图的高度可能会有很大差异,所以我想说对值进行标准化,计数图不支持估计器,因此使用条形图的估计器来查找相对值

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

change_width功能

关于python - 同一图中的条形图和计数图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59414738/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com