MatplotlibBars
Creating Bars
With Pyplot, you can use thebar()
function to draw bar graphs:
Example
Draw 4 bars:
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:
Thebar()
function takes arguments that describes the layout of the bars.
The categories and their values represented by thefirstandsecondargument as arrays.
Horizontal Bars
If you want the bars to be displayed horizontally instead of vertically,use thebarh()
function:
Example
Draw 4 horizontal bars:
import numpy as np
x = np.array(["A", "B", "C", "D"])
y = np.array([3, 8, 1, 10])
plt.barh(x, y)
plt.show()
Result:
Bar Color
Thebar()
andbarh()
take the keyword argumentcolor
to set the color of the bars:
Example
Draw 4 red bars:
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:
Color Names
You can use any of the140 supported color names.
Example
Draw 4 "hot pink" bars:
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:
Color Hex
Or you can useHexadecimal color values:
Example
Draw 4 bars with a beautiful green color:
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
Thebar()
takes the keyword argumentwidth
to set the width of the bars:
Example
Draw 4 very thin bars:
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:
The default width value is 0.8
Note: For horizontal bars, useheight
instead ofwidth
.
Bar Height
Thebarh()
takes the keyword argumentheight
to set the height of the bars:
Example
Draw 4 very thin bars:
import numpy as np
x = np.array(["A", "B", "C", "D"])
y = np.array([3, 8, 1, 10])
plt.barh(x, y, height = 0.1)
plt.show()
Result:
The default height value is 0.8