如何根据以下条件选择条形图条形图内文本批注的字体大小:
请仔细阅读图表和代码,以便更清楚地了解问题
因此,要求仅为:字体大小应与条形图中的条形图相对应
代码
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
# Plot styles
mpl.style.use("ggplot")
# data
fruits = pd.Series(index = ["Apples", "Oranges", "Watermelon"], data = [324,518, 258])
# Bar graph for Fruits
# figure
plt.figure(figsize = (7,5))
# bar graph
fruits.plot(kind = "bar", color = ["red", "orange", "green"], alpha = 0.6, width = 0.5, )
# percentage of each fruit type
categories = list(fruits.index)
categories_percent = [100*(value/fruits.sum()) for value in fruits ]
# categories annotations coordinates
ax = plt.gca() # get current axes
rects = ax.patches # rectangles axes of bars in the graph
# annotations
for i in range(len(categories)):
plt.annotate(f"{categories[i]} - {categories_percent[i] : 0.2f}%",
xy = (rects[i].get_x() + rects[i].get_width()/2,
rects[i].get_y() + (ax.get_yticks()[1] - ax.get_yticks()[0])*.2),
fontsize = [20,28,12][i], # Chosen by hit and trial for adjustment
color = "white",
ha = "center",
rotation = 90,
)
plt.ylabel("# Counts", fontsize = 15,)
plt.title("Distribution of Fruits", fontsize = 25, fontname = "Monospace", alpha = .6)
plt.xticks([])
plt.tight_layout(rect=[0, 0, 1, 1])
plt.show()
如何处理这行代码fontsize = [20,28,12][i], # Chosen by hit and trial for adjustment
以根据条形图区域动态调整字体大小
fontsize
更新现有注释y
作为高度的比例因子李>.get_height
视为图形的相对高度.get_height
李>.get_width
(不是get_width*x
),但是它只是一个常量,因为它是相对宽度李>对于figsize=(15,15):
对于figsize=(8,8):
对于figsize=(7,5):
相关问题 更多 >
编程相关推荐