Data Visualization 2
Data Visualization 2
Matplotlib
Basic Plots
1
Bar Chart
• When to use Bar chart
– Vertical bar charts are useful to compare numerical values across categories, such
as age groups,classes.
2
Bar Chart
• Create bar chart
– plt.bar(x,height,[width])# vertical bar plot
– plt.barh()# produces horizontal bar plot
– plt.bar(['A', 'B', 'C', 'D'], [20, 25, 40, 10])
–
3
Grouped Bar Chart
• When to use Grouped Bar chart
– Grouped bar charts are good for comparing among each element under
multiple categories,
4
Grouped Bar Chart
• Create bar chart with subcategory
– labels = ['A', 'B', 'C', 'D']
– x = np.arange(len(labels))
– width = 0.4
– plt.bar(x-width/2 , [20, 25, 40, 10], width)
– plt.bar(x+width/2, [30, 15, 30, 20], width)
– ax=plt.gca()# get instance of curr. axes
– plt.xticks(x)
– ax.set_xticklabels(labels)
5
Ex 1:Bar Plot for Movie Comparison
Use percentages in an interval of 20 for the y-axis and minor ticks in an
interval of 5.
6
Stacked Bar Chart
• When to use stacked bar chart
– Stacked bar charts are used to show how a category is divided into sub-categories
and the proportion of the sub-category, in comparison to the overall category
7
Stacked Bar Chart
• To create stacked bar chart
• It uses the same plt.bar function as bar charts.
• plt.bar(x, bars1)
• plt.bar(x, bars2, bottom=bars1)
• plt.bar(x, bars3, bottom=np.add(bars1, bars2))
8
Ex 2:Visualize Rest. Performance
9
Pie Chart
• When to use pie chart
– The aim of using a pie chart is to compare the contribution of each part to the
whole data.
– A pie chart works best if the sample data only has a few components
10
Pie Chart
• To create pie chart
– plt.pie(x, [explode], [labels], [autopct])
• x: Specifies the slice sizes.
• explode: (optional): Specifies the fraction of the radius offset for
each slice. The explode-array must have the same length as
• the x-array.
• Labels:(optional): Specifies the labels for each slice.
• autopct :(optional): Shows percentages inside the slices according to
the specified format string. Example: '%1.1f%%'.
11
–
Pie Chart
• Example
– plt.pie([0.4, 0.3, 0.2, 0.1], explode=(0.1, 0, 0, 0), labels=['A', 'B', 'C', 'D'])
12
Ex 3: A Pie Chart for Water Usage
13
Stacked Area Chart
• When to use Stacked area chart
– When the primary categorical variable is derived from a continuous feature, such as
periods of time, we have the option of using a stacked area chart rather than stacked
bars.
14
Stacked Area Chart
• To create stacked area chart
– plt.stackplot(x, y)
• x:Specifies the x-values of the data series..
• labels (Optional): Specifies the labels as a list or tuple for each data
series.
15
Stacked Area Chart
• Example
– plt.stackplot([1, 2, 3, 4], [2, 4, 5, 8], [1, 5, 4, 2])
–
16
Ex 4:Comparing Smartphone Sales
17