“I have generated a histogram graph, graph looks good except on the x-axis ticks are not positioned middle of the bar sometimes the ticks are randomly placed to the edges and center of the bar.
In the screenshot, ticks under the bars are randomly placed but I need ticks to be placed under the bar & its position should exactly mid position like 191.”
def generate_histogram(data_dict):
result_folder = 'graphs'
if not os.path.exists(result_folder):
os.makedirs(result_folder)
pdf_file = os.path.join(result_folder, '{filename?_{timestamp}.pdf")
with PdfPages(pdf_file) as pdf:
for key, values in data_dict.items):
plt.figure(figsize=(25, 20))
n, bins, patches = plt.hist(values, bins=38, edgecolor="black" , alpha=0.7, rwidth=0.8, botton=0, label=key)
if key.endswith("Width_in_ps'):
key_value = "Width in ps"
if key.endswith(Height_in_mV):
key_value = "Height in mv"
plt.xlabel(f' {key_valve}')
plt.ylabel('Count')
if key:
t1 = key.replace("in_ps", ""), replace(" in_m", "")
plt.title(t1)
# Calculate tick positions for the y-axis
max_count = int (max(n))
# Set y-axis ticks to include 0 and the maximum count
y_ticks = [0, max_count]
plt.yticks(y_ticks)
# Ensure unique x-axis tick values
unique_values = np.unique(values)
plt.xticks(unique_values, rotation=45) #To rotate values on x-axis ticks use thisline
# Annotate each bar with its count
for i in range(len(patches)):
if n[i] != 0:
plt.text(patches[i].get_x) + patches[i].get_width() / 2, patches[i].get_height()/1,
str(int(n[i])), ha='center', color='black') # Centering count on top of the bar
plt.tight_layout()
pdt.savefig()
plt.close()
print(f"33[92mPDF file '{pdf_file}' has been generated. 33[0m")`
generate_histogram(data_dict)
New contributor
Anvesh is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.