plt.bar_label变成百分数
时间: 2023-10-26 08:13:22 浏览: 229
可以使用 `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.pyplot as plt import pandas as pd plt.rcParams['font.sans-serif']=['Arial Unicode MS'] #设置中文字体为Arial Unicode MS plt.rcParams['axes.unicode_minus']=False #解决保存图像是负号'-'显示为方块的问题 df = pd.read_csv("vehicles-数据.csvv",encoding='gbk')带或是不带增压充电器(sCharger)的车的数量和年份的关系。展示不同年份带或是不带增压充电器汽车的数量或者百分比用groupbar展示
根据你提供的代码,以下是一个示例的代码,可以帮助你回答这些问题:
```
import pandas as pd
import matplotlib.pyplot as plt
# 读取CSV文件
df = pd.read_csv("vehicles-数据.csv", encoding='gbk')
# 将增压充电器(sCharger)列中的空值填充为“无”
df["sCharger"].fillna("无", inplace=True)
# 统计年份和增压充电器的交叉计数
count_df = pd.crosstab(df["year"], df["sCharger"])
# 计算每一年的总记录数量
total_records = count_df.sum(axis=1)
# 计算每一年增压充电器汽车的数量占比
scharger_percent = count_df["有"] / total_records
# 计算每一年未带增压充电器汽车的数量占比
no_scharger_percent = count_df["无"] / total_records
# 绘制图形
fig, ax = plt.subplots()
ax.bar(count_df.index, nocharger_percent, label="No Supercharger")
ax.bar(count_df.index, scharger_percent, bottom=nocharger_percent, label="With Supercharger")
ax.set_xlabel("Year")
ax.set_ylabel("Percentage")
ax.legend()
plt.show()
```
请替换"vehicles-数据.csv"为你的CSV文件名,并且替换"sCharger"和"year"为你数据集中的实际列名。这个示例代码可以帮助你统计带或是不带增压充电器汽车的数量和年份的关系,并使用分组条形图展示不同年份带或是不带增压充电器汽车的数量或者百分比。该图形使用两个颜色的条形来表示带或是不带增压充电器汽车的数量占比。
# 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轴的值分别设置为列中每个唯一值的出现次数和值本身。最后,函数在每个子图上绘制柱状图,并将数据标签添加到每个条形上。如果没有足够的子图来填充整个网格,则函数会删除空的子图以使图像更清晰。
阅读全文
相关推荐

















