Bars

What You'll Learn: In this tutorial, you'll discover how to use Matplotlib's bar() function to draw bar graphs. We'll cover creating bars, customizing bar colors, and adjusting bar widths.

Creating Bars

With Pyplot, you can use the bar() function to draw bar graphs. The bar() function takes arguments that describe the layout of the bars. The categories and their values are represented by the first and second arguments as arrays.

Example: Draw 4 bars

python
import matplotlib.pyplot as plt
import numpy as np

x = np.array(["A", "B", "C", "D"])
y = np.array([3, 8, 1, 10])

plt.bar(x, y)
plt.show()

Result:

Bar Color

The bar() and barh() functions take the keyword argument color to set the color of the bars.

Example: Draw 4 red bars

python
import matplotlib.pyplot as plt
import numpy as np

x = np.array(["A", "B", "C", "D"])
y = np.array([3, 8, 1, 10])

plt.bar(x, y, color='red')
plt.show()

Result:

You can also use any of the 140 supported color names.

Example: Draw 4 "hot pink" bars

python
import matplotlib.pyplot as plt
import numpy as np

x = np.array(["A", "B", "C", "D"])
y = np.array([3, 8, 1, 10])

plt.bar(x, y, color='hotpink')
plt.show()

Result:

Or you can use Hexadecimal color values.

Example: Draw 4 bars with a beautiful green color

python
import matplotlib.pyplot as plt
import numpy as np

x = np.array(["A", "B", "C", "D"])
y = np.array([3, 8, 1, 10])

plt.bar(x, y, color='#4CAF50')
plt.show()

Result:

Bar Width

The bar() function takes the keyword argument width to set the width of the bars. The default width value is 0.8.

Example: Draw 4 very thin bars

python
import matplotlib.pyplot as plt
import numpy as np

x = np.array(["A", "B", "C", "D"])
y = np.array([3, 8, 1, 10])

plt.bar(x, y, width=0.1)
plt.show()

Result:

Note: For horizontal bars, use height instead of width.

Try It Yourself: Fun Exercises

  1. Create a Bar Graph:
    • Draw a bar graph with your own data and customize the colors of the bars.
  2. Experiment with Bar Width:
    • Try setting different bar widths and observe how it affects the graph.
  3. Use Different Colors:
    • Use different color names and hexadecimal values to create colorful bar graphs.

Summary:

In this tutorial, we learned how to create bar graphs using Matplotlib in Python. We explored creating bars, customizing bar colors, and adjusting bar widths. Keep experimenting and have fun with Matplotlib in Python!