Data Science Explorer

Matplotlib Bars 본문

Python

Matplotlib Bars

grace21110 2023. 11. 9. 19:34
반응형
  • Creating bars 

Use bar() function to draw the bar graph. 

 

Example 

import matplotlib.pyplot as plt 
import numpy as np

x = np.array(["Grace", "Momo", "Anas", "David"])
y = np.array([3, 8, 1, 10])

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

Result 

 

  • Horizontal bars 

Use barh() to have your graph displayed horizontally.

 

Example 

import matplotlib.pyplot as plt
import numpy as np

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

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

Result

 

Bar Color 

You can adjust the color by using argument c. 

 

Example 

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 

 

  • Bar Width 

Use argument width to adjust the width. 

 

Example 

import matplotlib.pyplot as plt 
import numpy as np 

x = np.array(["Grace", "Dan", "Pearl", "Sara"])
y = np.array([8, 8, 2, 10])

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

Result 

 

  • Bar Height 

For horizontal bars (barh), it takes the keyword height to set the height of the bars instead of width.

 

Example

import matplotlib.pyplot as plt 
import numpy as np 

x = np.array(["Grace", "Dan", "Pearl", "Sara"])
y = np.array([8, 8, 2, 10])

plt.barh(x, y, height = 0.2)
plt.show()

Result 

'Python' 카테고리의 다른 글

Matplotlib Pie Charts  (0) 2023.11.11
Matplotlib Histograms  (0) 2023.11.10
Matplotlib Scatter  (0) 2023.11.08
Matplotlib Subplot  (0) 2023.11.07
Matplotlib: Matplotlib Adding Grid Lines  (0) 2023.11.06