Course Content
Python Indentation, Comments and Variables
0/2
Object Oriented Programming in Python
0/1
Exception Handling in Python
0/1
Sending emails with Python
0/1
Unit test in python programming
0/1
Python programming (zero to advance!!!)
About Lesson

Matplotlib Bars

In Matplotlib, you can create bar plots to visualize categorical data using bars of different heights. Bar plots are useful for comparing different categories or displaying the distribution of data across categories.

 

 

WHEN TO USE BAR GRAPHS
Bar graphs are commonly used in situations where you want to visualize and compare categorical data or discrete values. Here are some scenarios where bar graphs are particularly useful:

1. Comparing Categories: Bar graphs are ideal for comparing the values of different categories or groups. For example, you might use a bar graph to compare sales figures for different products, performance metrics for different teams, or demographic data for different age groups.

2. Showing Distribution: Bar graphs can effectively display the distribution of data within categories. For instance, you can use a bar graph to show the frequency of occurrence of various categories or the proportion of each category within a dataset.

3. Tracking Changes Over Time: While line graphs are typically used for time-series data, bar graphs can also be useful for visualizing changes in categorical data over time. Each bar represents a specific time period, and you can compare the values across different time periods to identify trends or patterns.

4. Presenting Survey Results: Bar graphs are commonly used to present survey results or responses to multiple-choice questions. Each bar represents a different response option, and the height of the bar indicates the frequency or percentage of respondents who selected that option.

5. Comparing Performance: Bar graphs are often employed in business and finance to compare the performance of different entities, such as companies, departments, or individuals. You can use bar graphs to visualize metrics like revenue, profits, market share, or customer satisfaction scores across different entities.

6. Displaying Rankings: Bar graphs can be used to display rankings or orderings of items based on their values. You can arrange the bars in ascending or descending order to highlight the relative positions of different categories.

Overall, bar graphs are versatile and widely used in various fields to effectively communicate categorical data and comparisons between different groups or variables. They provide a clear and intuitive way to visualize information and identify patterns or insights within datasets.

 

Creating a Bar Plot

To create a basic bar plot in Matplotlib, you can follow these steps:

1. Import Matplotlib: First, you need to import the Matplotlib library, typically using the alias `plt`.

2. Prepare Data: Prepare your data in the form of categories and corresponding values. For example, you might have a list of categories and their respective counts or values.

3. Plotting the Bars: Use the `plt.bar()` function to plot the bars. Provide the categories as the x-axis values and the corresponding values as the y-axis values. You can also specify additional parameters such as color, width, and alignment of the bars.

4. Adding Labels and Title: Enhance the plot by adding labels to the x-axis and y-axis using `plt.xlabel()` and `plt.ylabel()`, respectively. You can also set a title for the plot using `plt.title()`.

5. Display the Plot: Finally, use `plt.show()` to display the plot.

Example:

“`python
import matplotlib.pyplot as plt

# Data
categories = [‘Category A’, ‘Category B’, ‘Category C’, ‘Category D’]
values = [10, 15, 7, 12]

# Plotting the bars
plt.bar(categories, values, color=’skyblue’)

# Adding labels and title
plt.xlabel(‘Categories’)
plt.ylabel(‘Values’)
plt.title(‘Bar Chart Example’)

# Display the plot
plt.show()
“`

This code will generate a simple bar chart with categories on the x-axis and values on the y-axis. You can customize the appearance of the plot by adjusting parameters such as colors, bar width, and alignment.

 

Horizontal Bars

Matplotlib Horizontal Bars

In Matplotlib, you can create horizontal bar plots to visualize categorical data with bars of different widths. Horizontal bar plots are useful for comparing categories or displaying the distribution of data across categories when the category names are long.

Creating a Horizontal Bar Plot

To create a horizontal bar plot in Matplotlib, you can follow these steps:

1. Import Matplotlib: Begin by importing the Matplotlib library, typically using the alias `plt`.

2. Prepare Data: Organize your data into categories and corresponding values. Each category will be represented by a horizontal bar, with its length proportional to its value.

3. Plotting the Bars: Use the `plt.barh()` function to plot the horizontal bars. Provide the categories as the y-axis values and the corresponding values as the x-axis values. You can also specify additional parameters such as color, height, and alignment of the bars.

4. Adding Labels and Title: Enhance the plot by adding labels to the x-axis and y-axis using `plt.xlabel()` and `plt.ylabel()`, respectively. You can also set a title for the plot using `plt.title()`.

5. Display the Plot: Finally, use `plt.show()` to display the plot.

Example:

“`python
import matplotlib.pyplot as plt

# Data
categories = [‘Category A’, ‘Category B’, ‘Category C’, ‘Category D’]
values = [10, 15, 7, 12]

# Plotting the horizontal bars
plt.barh(categories, values, color=’lightgreen’)

# Adding labels and title
plt.xlabel(‘Values’)
plt.ylabel(‘Categories’)
plt.title(‘Horizontal Bar Chart Example’)

# Display the plot
plt.show()
“`

This code will generate a simple horizontal bar chart with categories on the y-axis and values on the x-axis. You can customize the appearance of the plot by adjusting parameters such as colors, bar height, and alignment.

Bar Color

Below is an example code that demonstrates how to specify custom colors for bars in a bar plot using Matplotlib:

“`python
import matplotlib.pyplot as plt

# Data
categories = [‘Category A’, ‘Category B’, ‘Category C’, ‘Category D’]
values = [10, 15, 7, 12]
colors = [‘skyblue’, ‘salmon’, ‘lightgreen’, ‘orange’] # Custom colors for each bar

# Plotting the bars with custom colors
plt.bar(categories, values, color=colors)

# Adding labels and title
plt.xlabel(‘Categories’)
plt.ylabel(‘Values’)
plt.title(‘Bar Plot with Custom Colors’)

# Display the plot
plt.show()
“`

In this example, each bar in the plot is assigned a custom color specified in the `colors` list. You can adjust the colors as desired to match your visualization preferences or to convey specific meanings associated with each category.

Colors – using the names of the colour

Matplotlib supports a wide range of color names that you can use to specify colors for various plot elements. Here are some common color names:

1. ‘blue’
2. ‘green’
3. ‘red’
4. ‘cyan’
5. ‘magenta’
6. ‘yellow’
7. ‘black’
8. ‘white’

In addition to these basic color names, Matplotlib also supports various shades and tones of colors, as well as some named colors like ‘skyblue’, ‘salmon’, ‘lightgreen’, etc.

You can use these color names directly when specifying colors for plot elements like lines, markers, or bars in your Matplotlib plots. For example:

“`python
import matplotlib.pyplot as plt

# Data
x = [1, 2, 3, 4, 5]
y = [10, 15, 7, 12, 8]

# Plotting a line with a specific color
plt.plot(x, y, color=’green’)

# Plotting a scatter plot with a specific color
plt.scatter(x, y, color=’blue’)

# Plotting bars with specific colors
plt.bar(x, y, color=’salmon’)

# Display the plot
plt.show()
“`

In this example, ‘green’, ‘blue’, and ‘salmon’ are some of the color names used to specify the colors of the line, scatter plot markers, and bars, respectively. You can replace these color names with any other valid color names to customize the appearance of your plots.

Color hex codes are another way to specify colors in Matplotlib. Hex codes are six-digit alphanumeric codes that represent a specific color. Each pair of digits in a hex code represents the intensity of the red, green, and blue (RGB) components of the color, respectively.

For example:
– #FF0000 represents pure red (maximum intensity of red, no green, no blue).
– #00FF00 represents pure green (no red, maximum intensity of green, no blue).
– #0000FF represents pure blue (no red, no green, maximum intensity of blue).
– #FFFFFF represents white (maximum intensity of red, green, and blue).

You can use hex codes directly when specifying colors for plot elements like lines, markers, or bars in your Matplotlib plots. For example:

“`python
import matplotlib.pyplot as plt

# Data
x = [1, 2, 3, 4, 5]
y = [10, 15, 7, 12, 8]

# Plotting a line with a specific color hex code
plt.plot(x, y, color=’#FF5733′) # Coral color

# Plotting a scatter plot with a specific color hex code
plt.scatter(x, y, color=’#8A2BE2′) # Blue Violet color

# Plotting bars with specific color hex codes
plt.bar(x, y, color=’#FFD700′) # Gold color

# Display the plot
plt.show()
“`

In this example, ‘#FF5733’, ‘#8A2BE2’, and ‘#FFD700’ are hex codes used to specify the colors of the line, scatter plot markers, and bars, respectively. You can replace these hex codes with any other valid hex codes to customize the appearance of your plots.

Bar Width

In Matplotlib, you can adjust the width of bars in a bar plot using the `width` parameter when plotting the bars. The `width` parameter specifies the width of each bar relative to the width of the entire category. By default, the width is set to 0.8, but you can adjust it to make the bars wider or narrower as needed.

Here’s how you can specify the width of bars in a bar plot:

“`python
import matplotlib.pyplot as plt

# Data
categories = [‘A’, ‘B’, ‘C’, ‘D’]
values = [15, 20, 18, 25]

# Plotting the bar chart with custom bar width
plt.bar(categories, values, width=0.5) # Adjust width as needed

# Adding labels and title
plt.xlabel(‘Categories’)
plt.ylabel(‘Values’)
plt.title(‘Bar Chart with Custom Bar Width’)

# Display the plot
plt.show()
“`

In this example, the `width` parameter is set to `0.5`, which makes the bars narrower than the default width. You can adjust the value of the `width` parameter to make the bars wider or narrower according to your preference and the requirements of your visualization.

Bar Height

In Matplotlib, when you’re creating horizontal bar plots, the height of the bars can be adjusted using the `height` parameter. This parameter specifies the height of each bar relative to the height of the entire category.

Here’s an example demonstrating how to adjust the height of bars in a horizontal bar plot:

“`python
import matplotlib.pyplot as plt

# Data
categories = [‘A’, ‘B’, ‘C’, ‘D’]
values = [15, 20, 18, 25]

# Plotting the horizontal bar chart with custom bar height
plt.barh(categories, values, height=0.5) # Adjust height as needed

# Adding labels and title
plt.xlabel(‘Values’)
plt.ylabel(‘Categories’)
plt.title(‘Horizontal Bar Chart with Custom Bar Height’)

# Display the plot
plt.show()
“`

In this example, the `height` parameter is set to `0.5`, which makes the bars shorter than the default height. You can adjust the value of the `height` parameter to make the bars taller or shorter based on your visualization requirements.

 

Join the conversation