plt.bar_label变成百分数
时间: 2023-10-26 18:13:22 浏览: 62
可以使用 `plt.bar_label()` 方法的 `labels` 参数来设置标签的格式。以下是一个将标签转换为百分比格式的示例代码:
```python
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
x = ['A', 'B', 'C', 'D']
y = [0.25, 0.35, 0.2, 0.2]
bars = ax.bar(x, y)
ax.bar_label(bars, labels=[f"{val*100:.1f}%" for val in y])
plt.show()
```
这个例子中,我们使用了 f-string 格式化字符串来将标签转换为百分比格式,然后将它们传递给 `plt.bar_label()` 方法的 `labels` 参数。在这个例子中,我们使用了 `:.1f` 格式选项来保留一位小数。你可以根据需要调整这些值。
相关问题
import matplotlib as mpl import matplotlib.pyplot as plt plt.subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=None, hspace=0.5) t=np.arange(0.0,2.0,0.1) s=np.sin(t*np.pi) plt.subplot(2,2,1) #要生成两行两列,这是第一个图 import numpy as np import matplotlib.pyplot as plt x = np.arange(1,13) y1 = np.array([53673, 57571, 58905, 55239, 49661, 49510, 49163, 57311, 59187, 60074, 57109, 52885]) plt.plot(x, y1) plt.title('近13天登录人数') plt.show() plt.subplot(2,2,2) #两行两列,这是第二个图 import numpy as np import matplotlib.pyplot as plt plt.subplots_adjust(top=0.85) x = np.arange(12) y = np.array([70887, 64957, 62508, 66471, 54972, 46245, 64083, 67090, 64991, 88504, 79404, 68253,]) bar_width = 0.3 plt.bar(x, y, tick_label=['1月', '2月', '3月', '4月', '5月', '6月', '7月', "8月", "9月", "10月", '11月', '12月'],width=bar_width) plt.title('近12个月人数') plt.show() plt.subplot(2,2,3)#两行两列,这是第三个图 import matplotlib.pyplot as plt plt.subplots_adjust(top=0.85) plt.style.use('fivethirtyeight') languages = ['steam', 'ubisoft'] popularity = [78,22] plt.pie(popularity) plt.tight_layout() plt.pie(popularity, labels=languages, autopct='%1.1f%%') plt.title('游戏平台登录占比') plt.subplot(2,2,4)#两行两列,这是第四个图 import numpy as np from matplotlib import pyplot as plt ages_x = [1, 2, 3, 4, 5, ] x_indexes = np.arange(len(ages_x)) width = 0.33 dev_y = [64050, 65168, 75588, 75590, 60097] py_dev_y = [57809, 56101, 70605, 63437, 56756] plt.bar(x_indexes, dev_y, width=width, label="2022") plt.bar(x_indexes + width, py_dev_y, width=width, label="2023") plt.xlabel("月份") plt.ylabel("平均在线人数") plt.title("2022和2023一到五月在线人数对比") plt.legend() plt.xticks(ticks = x_indexes, labels = ages_x) plt.show()
你刚才的代码中,第三个子图中的饼图有一些问题。虽然你使用了pie函数绘制了饼图,但是没有正确地添加标签和百分比。正确的代码应该是这样的:
```python
plt.subplot(2,2,3)
plt.subplots_adjust(top=0.85)
plt.style.use('fivethirtyeight')
languages = ['steam', 'ubisoft']
popularity = [78,22]
plt.pie(popularity, labels=languages, autopct='%1.1f%%')
plt.title('游戏平台登录占比')
plt.show()
```
这样做可以让饼图正确地显示游戏平台的登录占比,并显示出每个部分所占的百分比。
# Look through unique values in each categorical column categorical_cols = train_df.select_dtypes(include="object").columns.tolist() for col in categorical_cols: print(f"{col}", f"Number of unique entries: {len(train_df[col].unique().tolist())},") print(train_df[col].unique().tolist()) def plot_bar_chart(df, columns, grid_rows, grid_cols, x_label='', y_label='', title='', whole_numbers_only=False, count_labels=True, as_percentage=True): num_plots = len(columns) grid_size = grid_rows * grid_cols num_rows = math.ceil(num_plots / grid_cols) if num_plots == 1: fig, axes = plt.subplots(1, 1, figsize=(12, 8)) axes = [axes] # Wrap the single axes in a list for consistent handling else: fig, axes = plt.subplots(num_rows, grid_cols, figsize=(12, 8)) axes = axes.ravel() # Flatten the axes array to iterate over it for i, column in enumerate(columns): df_column = df[column] if whole_numbers_only: df_column = df_column[df_column % 1 == 0] ax = axes[i] y = [num for (s, num) in df_column.value_counts().items()] x = [s for (s, num) in df_column.value_counts().items()] ax.bar(x, y, color='blue', alpha=0.5) try: ax.set_xticks(range(x[-1], x[0] + 1)) except: pass ax.set_xlabel(x_label) ax.set_ylabel(y_label) ax.set_title(title + ' - ' + column) if count_labels: df_col = df_column.value_counts(normalize=True).mul(100).round(1).astype(str) + '%' for idx, (year, value) in enumerate(df_column.value_counts().items()): if as_percentage == False: ax.annotate(f'{value}\n', xy=(year, value), ha='center', va='center') else: ax.annotate(f'{df_col[year]}\n', xy=(year, value), ha='center', va='center', size=8) if num_plots < grid_size: for j in range(num_plots, grid_size): fig.delaxes(axes[j]) # Remove empty subplots if present plt.tight_layout() plt.show()
这段代码定义了一个名为plot_bar_chart的函数,它可以绘制柱状图。函数的输入包括一个数据框(df)、一个列名的列表(columns)、网格的行数和列数(grid_rows和grid_cols)、x轴和y轴标签(x_label和y_label)、标题(title)、是否只显示整数(whole_numbers_only)、是否在图上显示数据标签(count_labels)、以及是否以百分比形式显示数据标签(as_percentage)。
在函数内部,它首先计算需要绘制的子图的数量,然后根据网格的行数和列数创建子图。接下来,对于每个给定的列名,函数从数据框中选择该列,并将其存储在变量df_column中。如果whole_numbers_only为True,则函数只绘制整数值。接着,函数将x轴和y轴的值分别设置为列中每个唯一值的出现次数和值本身。最后,函数在每个子图上绘制柱状图,并将数据标签添加到每个条形上。如果没有足够的子图来填充整个网格,则函数会删除空的子图以使图像更清晰。