Histogram
A histogram is basically used to represent data in the form of some groups. It is a type of bar plot where the X-axis represents the bin ranges while the Y-axis gives information about frequency. It can be created using the px.histogram() method.
Syntax:
plotly.express.histogram(data_frame=None, x=None, y=None, color=None, facet_row=None, facet_col=None, barnorm=None, histnorm=None, nbins=None, title=None, template=None, width=None, height=None)
Example:
Python3
import plotly.express as px # using the dataset df = px.data.tips() # plotting the histogram fig = px.histogram(df, x = "total_bill" ) # showing the plot fig.show() |
Output:
Let’s customize the above graph. Customizations that we will be using are –
- color: To color the bars
- nbins: To set the number of bins
- histnorm: Mode through which the bins are represented. Different values that can be passed using this argument are-
- percent or probability: The output of histfunc for a given bin is divided by the sum of the output of histfunc for all bins.
- density: The output of histfunc for a given bin is divided by the size of the bin.
- probability density: The output of histfunc for a given bin is normalized such that it corresponds to the probability that a random
- barmode: Can be either ‘group’, ‘overlay’ or ‘relative’.
- group: Bars are stacked above zero for positive values and below zero for negative values
- overlay: Bars are drawn on the top of each other
- group: Bars are placed beside each other.
Example:
Python3
import plotly.express as px # using the dataset df = px.data.tips() # plotting the histogram fig = px.histogram(df, x = "total_bill" , color = 'sex' , nbins = 50 , histnorm = 'percent' , barmode = 'overlay' ) # showing the plot fig.show() |
Output:
Using Plotly for Interactive Data Visualization in Python
Plotly is an open-source module of Python which is used for data visualization and supports various graphs like line charts, scatter plots, bar charts, histograms, area plot, etc. In this article, we will see how to plot a basic chart with plotly and also how to make a plot interactive. But before starting you might be wondering why there is a need to learn plotly, so let’s have a look at it.