79156782

Date: 2024-11-04 19:46:57
Score: 1
Natty:
Report link

well for that as petition of fahim the solution that I found to show a pseudo grouped-stacked bar was to use .patches method, its function is to show or in this case to change the coords of the objects of the plot. The con I found is that the plot only looks good if you make only 2 groups, because the x-axis labels do not change its position (IDK if you can add labeling coords, gonna find out). So the censored code is this

pivot_table = df_to_pivot.pivot_table(
    index=['week', 'column_to_group_by'],
    columns='column_to_stack',
    values='Value_to_show',
    aggfunc='sum',
    fill_value=0 #This fills the nan values from the pivot table
)

# Setting the plot
ax = pivot_table.plot(kind='bar', stacked=True, figsize=(16,6))

# Custom x-axis labels
new_labels= [f'{week}/{group_by}' for week, group_by in pivot_table.index]
ax.set_xticklabels(new_labels, rotation=45,ha='right')

# Placing labels


# Adding labels and title
plt.xlabel('X_Axis_label')
plt.ylabel('Y_Axis_label')
plt.title('Title')
ax.legend(title='Legend_Title',bbox_to_anchor=(0., 1.02, 1., .102), loc='lower left', ncols=7, mode="expand", borderaxespad=0.)
plt.tight_layout()
#plt.grid()

plt.savefig(f'{root_file_path}name.png', format='png', bbox_inches='tight', dpi=300)

variable_to = 0 # This part of the code is the one that displace the columns ploted and makes them look like grouped by bars, important to know that no matter the quantity of the bar, it will always be plotted, so be carefull using this for loop as the grouping by technique
for i in range(len(ax.patches)):
    variable_to += 1
    if variable_to % 2 != 0:
        ax.patches[i].set_x(ax.patches[i].get_x()+0.125)
    else:
        ax.patches[i].set_x(ax.patches[i].get_x()-0.125)


# Show the plot
plt.show()

I hope you find it usefull, and help me improving the code <3

Reasons:
  • Blacklisted phrase (1): help me
  • Long answer (-1):
  • Has code block (-0.5):
  • Self-answer (0.5):
  • Low reputation (1):
Posted by: Burritodeltodo