#--------------------------------------------------------------------------------------------# Copyright (c) Microsoft Corporation. All rights reserved.# Licensed under the MIT License. See LICENSE.txt in the project root for license information.# --------------------------------------------------------------------------------------------importpandasaspdimportmatplotlib.pyplotaspltimportnumpyasnpimportseabornassns
[docs]defcreate_bar_asis(data,group_var,bar_var,title=None,subtitle=None,caption=None,ylab=None,xlab=None,percent=False,bar_colour="default",rounding=1):""" Create a bar chart with customizable options. Parameters: - data: DataFrame, the data to be plotted. - group_var: str, the variable to be grouped by on the x-axis. - bar_var: str, the variable to be plotted on the y-axis. - title: str, optional, title of the plot. - subtitle: str, optional, subtitle of the plot. - caption: str, optional, caption of the plot. - ylab: str, optional, label for the y-axis. - xlab: str, optional, label for the x-axis. - percent: bool, optional, whether to display values as percentages. - bar_colour: str, optional, color of the bars. Available options: "default", "alert", "darkblue". - rounding: int, optional, number of decimal places to round the values. Returns: - None: Displays the plot. """# Set default colors if not specifiedifbar_colour=="default":bar_colour="#34b1e2"elifbar_colour=="alert":bar_colour="#FE7F4F"elifbar_colour=="darkblue":bar_colour="#1d627e"# Determine upper limit for text color adjustmentup_break=data[bar_var].max()*1.3# Create the plotfig,ax=plt.subplots()bars=ax.bar(data[group_var],data[bar_var],color=bar_colour)# Add text labels on the barsforbarinbars:height=bar.get_height()ax.text(bar.get_x()+bar.get_width()/2,height,round(height,rounding)ifnotpercentelsef'{height:.{rounding}f}%'ifpercentelsef'{height:.{rounding}f}',ha='center',va='bottom',color="#FFFFFF"ifheight>up_breakelse"#000000",size=10)# Set labels and titleax.set_xlabel(ylab)ax.set_ylabel(xlab)ax.set_title(title)# Rotate x-axis labels for better readabilityplt.xticks(rotation=45,ha='right')# Show the plotplt.show()