In This Article, You Will Learn About Python Matplotlib Scatter.
Python Matplotlib Bars – Before moving ahead, let’s take a look at Python Matplotlib Scatter
Table of Contents
Create Bars
To draw the bar graphs, we can use the bar() function with Pyplot.
It takes two arguments –
Category: It classifies the name to each bar on the based category name.
Values: It takes a number as a value.
Note: Both arguments are taken as an array.
Example: Draw 2 bars in the graph.
import matplotlib.pyplot as plt
import numpy as np
x = np.array(["A", "B"])
y = np.array([20, 26])
plt.bar(x, y)
plt.show()
Example: Draw 4 bars in graph.
import matplotlib.pyplot as plt
import numpy as np
x = np.array(["A", "B", "C", "D"])
y = np.array([20, 26, 17, 31])
plt.bar(x, y)
plt.show()
Horizontal Bars
To draw horizontal bars, we can use barh() function with Pyplot.
Example: Draw 2 bars horizontally in a graph.
import matplotlib.pyplot as plt
import numpy as np
x = np.array(["A", "B"])
y = np.array([20, 26])
plt.barh(x, y)
plt.show()
Example: Draw 4 bars horizontally in a graph.
import matplotlib.pyplot as plt
import numpy as np
x = np.array(["A", "B", "C", "D"])
y = np.array([20, 26, 17, 31])
plt.barh(x, y)
plt.show()
Bar Color
To set the color in the bars, we can pass an argument color to bar() and barh() functions.
Example: Draw 2 bars with green color.
import matplotlib.pyplot as plt
import numpy as np
x = np.array(["A", "B"])
y = np.array([20, 26])
plt.bar(x, y, color = "green")
plt.show()
Example: Draw 4 bars horizontally with orange color.
import matplotlib.pyplot as plt
import numpy as np
x = np.array(["A", "B", "C", "D"])
y = np.array([20, 26, 32, 36])
plt.barh(x, y, color = "orange")
plt.show()
Color Names
We have 140 color names to apply on bars.
Click to DOWNLOAD FILE
Example: Draw 3 “DarkGreen” bars.
import matplotlib.pyplot as plt
import numpy as np
x = np.array(["A", "B", "C"])
y = np.array([20, 26, 32])
plt.barh(x, y, color = "DarkGreen")
plt.show()
Color Hex
Also, we can use HTML color code.
Example: Draw 3 “DarkGreen” bars.
import matplotlib.pyplot as plt
import numpy as np
x = np.array(["A", "B", "C"])
y = np.array([20, 26, 32])
plt.bar(x, y, color = "#006400")
plt.show()
Bar Width
To set the width of the bars, we can pass an argument width in the bar() function.
Example: Set the width of bars as 0.2.
import matplotlib.pyplot as plt
import numpy as np
x = np.array(["A", "B", "C"])
y = np.array([20, 26, 32])
plt.bar(x, y, width = 0.2)
plt.show()
Note: The default value of width is 0.8.
Pass an argument height in the bar() function for horizontal bars.
Example: Set the height of bars as 0.2.
import matplotlib.pyplot as plt
import numpy as np
x = np.array(["A", "B", "C"])
y = np.array([20, 26, 32])
plt.barh(x, y, height = 0.2)
plt.show()