How to draw an histogram with multiple categories in python

2024/10/11 18:25:54

I am a freshman in python, and I have a problem of how to draw a histogram in python.

First of all, I have ten intervals that are divided evenly according to the length of flowers' petal, from min to max. Thus I can separate flowers into ten intervals based on petals.

The number of flowers' kind is three, so I want to draw a histogram to describe the distribution of different kinds of flowers in different intervals(bins). And in the same bin, different flowers have different colors.

I know the hist functions in Matplotlib, but I don't know how to use it to draw pictures like below.

wanted histogram

The data are Lbins = [0.1 , 0.34, 0.58, 0.82, 1.06, 1.3 , 1.54, 1.78, 2.02, 2.26, 2.5 ] and Data_bins is an array of shape (number of flowers, 3).

Answer

Here is an example of an histogram with multiple bars for each bins using hist from Matplotlib:

import numpy as np
import matplotlib.pyplot as pltlength_of_flowers = np.random.randn(100, 3)
Lbins = [0.1 , 0.34, 0.58, 0.82, 1.06, 1.3 , 1.54, 1.78, 2.02, 2.26, 2.5 ]
# Lbins could also simply the number of wanted binscolors = ['red','yellow', 'blue']
labels = ['red flowers', 'yellow flowers', 'blue flowers']
plt.hist(length_of_flowers, Lbins,histtype='bar',stacked=False,  fill=True,label=labels,alpha=0.8, # opacity of the barscolor=colors,edgecolor = "k")# plt.xticks(Lbins) # to set the ticks according to the bins
plt.xlabel('flower length'); plt.ylabel('count');
plt.legend();
plt.show()

which gives:

example hist

Edit: Solution for pre-binned data inspired from this matplotlib demo. The position of each bar is custom computed. I slightly modified the data by replacing zero values to verify correct alignment.

import numpy as np
import matplotlib.pyplot as pltbinned_data = np.array([[41., 3., 3.], [ 8., 3., 3.], [ 1., 2., 2.], [ 2., 7., 3.],[ 0., 20., 0.], [ 1., 21., 1.], [ 1., 2., 4.], [ 3., 4., 23.],[ 0., 0., 9.], [ 3., 1., 14.]]).T# The shape of the data array have to be:
#  (number of categories x number of bins)
print(binned_data.shape)  # >> (3, 10)x_positions = np.array([0.1, 0.34, 0.58, 0.82, 1.06, 1.3, 1.54, 1.78, 2.02, 2.26])number_of_groups = binned_data.shape[0]
fill_factor =  .8  # ratio of the groups width# relatively to the available space between ticks
bar_width = np.diff(x_positions).min()/number_of_groups * fill_factorcolors = ['red','yellow', 'blue']
labels = ['red flowers', 'yellow flowers', 'blue flowers']for i, groupdata in enumerate(binned_data): bar_positions = x_positions - number_of_groups*bar_width/2 + (i + 0.5)*bar_widthplt.bar(bar_positions, groupdata, bar_width,align='center',linewidth=1, edgecolor='k',color=colors[i], alpha=0.7,label=labels[i])plt.xticks(x_positions);
plt.legend(); plt.xlabel('flower length'); plt.ylabel('count');

which gives:

example with binned data

https://en.xdnf.cn/q/118291.html

Related Q&A

Turtle in Tkinter creating multiple windows

I am attempting to create a quick turtle display using Tkinter, but some odd things are happening.First two turtle windows are being created, (one blank, one with the turtles), secondly, any attempt of…

Array tkinter Entry to Label

Hey Guys I am beginner and working on Project Linear and Binary search GUI application using Tkinter, I want to add multiple Entry boxes values to label and in an array here, I tried but its not workin…

Grid search and cross validation SVM

i am implementing svm using best parameter of grid search on 10fold cross validation and i need to understand prediction results why are different i got two accuracy results testing on training set not…

Accessing dynamically created tkinter widgets

I am trying to make a GUI where the quantity of tkinter entries is decided by the user.My Code:from tkinter import*root = Tk()def createEntries(quantity):for num in range(quantity):usrInput = Entry(roo…

Graphene-Django Filenaming Conventions

Im rebuilding a former Django REST API project as a GraphQL one. I now have queries & mutations working properly.Most of my learning came from looking at existing Graphene-Django & Graphene-Py…

Summing up CSV power plant data by technology and plant name

Ive got a question regarding the Form 860 data about US power plants.It is organized block-wise and not plant-wise. To become useful, the capacity numbers must be summed up.How may I get the total capa…

Send and receive signals from another class pyqt

I am needing a way to receive signals sent by a Class to another class. I have 2 classes: In my first class I have a function that emits a signal called asignal In my second class I call the first cla…

I can not add many values in one function

I have a gui applicationI put text into text box1, text box2,………… text box70 ,and then click on the pushButton, The function return_text () in the module_b.py be called. Now I can call one instance…

Close browser popup in Selenium Python

I am scraping a page using Selenium, Python. On opening the page one Popup appears. I want to close this popup anyway. I tried as below:url = https://shopping.rochebros.com/shop/categories/37browser = …

How can I replace certain string in a string in Python?

I am trying to write two procedures to replace matched strings in a string in python. And I have to write two procedures. def matched_case(old new): .........note: inputs are two strings, it returns a…