Python中的 Matplotlib.pyplot.barh()函数
条形图或条形图是表示数据类别的图形,矩形条的长度和高度与它们所代表的值成正比。条形图可以水平或垂直绘制。条形图描述了离散类别之间的比较。图的一个轴代表正在比较的特定类别,而另一个轴代表与这些类别对应的测量值。
创建水平条形图
Python中的matplotlib API 提供了barh()函数,该函数可用于 MATLAB 风格的使用或作为面向对象的 API。与轴一起使用的barh()函数的语法如下:-
Syntax: matplotlib.pyplot.barh(y, width, height=0.8, left=None, *, align=’center’, **kwargs)
下面描述了上述函数的一些位置和可选参数:Parameters Description Y Co-ordinates of the Y bars. width Scalar or array like, denotes the width of the bars. height Scalar or array like, denotes the height of the bars(default value is 0.8). left Scalar or sequence of scalars, denotes X co-ordinates on the left sides of the bars(default value is 0). align {‘center’, ‘edge’}aligns the base of the Y co-ordinates(default value is center). color Scalar or array like, denotes the color of the bars. edgecolor Scalar or array like, denotes the edge color of the bars. linewidth Scalar or array like, denotes the width of the bar edges. tick_label Scalar or array like, denotes the tick labels of the bars(default value is None).
该函数根据给定的参数创建一个以矩形为边界的水平条形图。以下是barh()方法创建水平条形图的一个简单示例,该条形图表示就读于某个机构不同课程的学生人数。
示例 1:
Python3
import numpy as np
import matplotlib.pyplot as plt
# creating the dataset
data = {'C': 20, 'C++': 15, 'Java': 30,
'Python': 35}
courses = list(data.keys())
values = list(data.values())
fig = plt.figure(figsize=(10, 5))
# creating the bar plot
plt.barh(courses, values, color='maroon')
plt.xlabel("Courses offered")
plt.ylabel("No. of students enrolled")
plt.title("Students enrolled in different courses")
plt.show()
Python3
import pandas as pd
from matplotlib import pyplot as plt
# Read CSV into pandas
data = pd.read_csv(r"Downloads/cars1.csv")
data.head()
df = pd.DataFrame(data)
name = df['car'].head(12)
price = df['price'].head(12)
# Figure Size
fig, ax = plt.subplots(figsize=(16, 9))
# Horizontal Bar Plot
ax.barh(name, price)
# Remove axes splines
for s in ['top', 'bottom', 'left', 'right']:
ax.spines[s].set_visible(False)
# Remove x, y Ticks
ax.xaxis.set_ticks_position('none')
ax.yaxis.set_ticks_position('none')
# Add padding between axes and labels
ax.xaxis.set_tick_params(pad=5)
ax.yaxis.set_tick_params(pad=10)
# Add x, y gridlines
ax.grid(b=True, color='grey',
linestyle='-.', linewidth=0.5,
alpha=0.2)
# Show top values
ax.invert_yaxis()
# Add annotation to bars
for i in ax.patches:
plt.text(i.get_width()+0.2, i.get_y()+0.5,
str(round((i.get_width()), 2)),
fontsize=10, fontweight='bold',
color='grey')
# Add Plot Title
ax.set_title('Sports car and their price in crore',
loc='left', )
# Add Text watermark
fig.text(0.9, 0.15, 'Jeeteshgavande30', fontsize=12,
color='grey', ha='right', va='bottom',
alpha=0.7)
# Show Plot
plt.show()
输出 :
这里 plt.barh(courses, values, color='maroon') 用于指定以课程列为 Y 轴,以值为 X 轴绘制条形图。 color 属性用于设置条形的颜色(在本例中为栗色)。 plt.xlabel(“Courses provided”) 和 plt.ylabel(“students registered”) 用于标记相应的轴。plt.title( ) 用于为 graph.plt.show() 制作标题,用于使用前面的命令将图形显示为输出。
示例 2:
蟒蛇3
import pandas as pd
from matplotlib import pyplot as plt
# Read CSV into pandas
data = pd.read_csv(r"Downloads/cars1.csv")
data.head()
df = pd.DataFrame(data)
name = df['car'].head(12)
price = df['price'].head(12)
# Figure Size
fig, ax = plt.subplots(figsize=(16, 9))
# Horizontal Bar Plot
ax.barh(name, price)
# Remove axes splines
for s in ['top', 'bottom', 'left', 'right']:
ax.spines[s].set_visible(False)
# Remove x, y Ticks
ax.xaxis.set_ticks_position('none')
ax.yaxis.set_ticks_position('none')
# Add padding between axes and labels
ax.xaxis.set_tick_params(pad=5)
ax.yaxis.set_tick_params(pad=10)
# Add x, y gridlines
ax.grid(b=True, color='grey',
linestyle='-.', linewidth=0.5,
alpha=0.2)
# Show top values
ax.invert_yaxis()
# Add annotation to bars
for i in ax.patches:
plt.text(i.get_width()+0.2, i.get_y()+0.5,
str(round((i.get_width()), 2)),
fontsize=10, fontweight='bold',
color='grey')
# Add Plot Title
ax.set_title('Sports car and their price in crore',
loc='left', )
# Add Text watermark
fig.text(0.9, 0.15, 'Jeeteshgavande30', fontsize=12,
color='grey', ha='right', va='bottom',
alpha=0.7)
# Show Plot
plt.show()
输出: