微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在 Python 中优化基于数据框的堆积条形图

如何解决在 Python 中优化基于数据框的堆积条形图

我正在尝试使用 PyCharm 创建堆积条形图。 我正在使用 matplotlib 来充分探索它在简单数据可视化方面的潜力。

我的原始代码是用于显示不同团队的周期时间的组图表栏。这些信息来自数据帧。该图表还包括自动标记功能(即每个条的高度 = 连续变量)。

Original Bar Chart - Group Distribution

我正在尝试在堆积条形图中转换此类组条形图。由于两个因素,以下代码需要改进:

  • 变量标签的小数位数过多:分组条形图未出现此问题。 csv 文件和派生的数据框没有改变。我正在努力理解是否以及在哪里使用 round 命令。我猜这个问题要么与自动标记功能有关,因为使用的数据类型是浮点数(我需要看到至少 1 个小数)。
  • 数据标签被置换:由于为分隔条创建了自动标签功能标签总是与我想要的距离匹配(基于垂直偏移)。不幸的是,我没有弄清楚如何确保这个距离相当中心(参见我的例子,漏斗时间的值是在小队时间的高度,反之亦然)。按逻辑,问题应该是每个变量的高度是提前定义的(参见代码中的 rects3,底部的值)但我不知道如何在我的自动标记变量中反映这一点.

Messed up Stacked chart

问题是代码中的哪些内容必须更改才能使周期时间值居中?

代码(您的注释以粗体标记):

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

'''PART 1 - Preprocess data -----------------------------------------------'''
#Directory or link of my CSV. This can be used also if you want to use API.
csv1 = r"C:\Users\AndreaPaviglianiti\Downloads\CT_Plot_DF.csv"

#Create and read dataframe. This is just to check the DF before plotting
df = pd.read_csv(csv1,sep=',',engine= 'python')
print(df,'\n')

#Extract columns as lists
squads = df['squad_Name'].astype('str') #for our horizontal axis
funnel = df['Funnel_Time'].astype('float')
squadt = df['squad_Time'].astype('float')
wait = df['Waiting_Time'].astype('float')

这里我尝试设置四舍五入但没有成功

'''PART 2 - Create the Bar Plot / Chart ----------------------------------'''
x = np.arange(len(squads))  #our labels on x will be the squads' names
width = 0.2  # the width of the bars. The bigger value,the larger bars
distance = 0.2
#Create objects that will be used as subplots (fig and ax).
#Each "rects" is the visualization of a yn value. first witdth is distance between X values,# the second is the real width of bars.


fig,ax = plt.subplots()
rects1 = ax.bar(x,funnel,width,color='red',label='Funnel Time')
rects2 = ax.bar(x,squadt,color='green',bottom=funnel,label='squad Time')
rects3 = ax.bar(x,wait,bottom=funnel+squadt,color='purple',label='Waiting Time')


# Add some text for labels,title and custom x-axis tick labels,etc.
ax.set_ylabel('Mean Cycle Time (h)')
ax.set_xlabel('\n squads')
ax.set_title("squad's Cycle Time Comparison in Dec-2020 \n (in mean Hours)")
ax.set_xticks(x)
ax.set_xticklabels(squads)
ax.legend()
fig.align_xlabels() #align labels to columns

# The function to display values above the bars
def autolabel(rects):
    """Attach a text label above each bar in *rects*,displaying its height."""
    for rect in rects:
        height = rect.get_height()
        ax.annotate('{}'.format(height),xy=(rect.get_x() + rect.get_width()/2,height),xytext=(0,3),# 3 points vertical offset
                    textcoords="offset points",ha='center',va='bottom')

在这里,我尝试更改 xytext="center" 但出现错误,我应该仅使用坐标还是有其他方法可以将位置从高度更改为中心? >

#We will label only the most recent information. To label both add to the code "autolabel(rects1)"
    autolabel(rects1)
    autolabel(rects2)
    autolabel(rects3)
    fig.tight_layout()
    
    '''PART 3 - Execute -------------------------------------------------------'''
    plt.show()

感谢您的帮助!

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。