我有一個堆疊條形圖,它使用顏色顯示了 NBA 球隊之間年齡組的分布,代碼如下所示:
import matplotlib.pyplot as mpl
import matplotlib.cm as mcm
import pandas as pd
import numpy as np
from typing import List, Tuple
def read_to_df(file_path: str) -> pd.DataFrame:
return pd.read_excel(file_path, index_col = 0)
def color_to_hex(color: Tuple[float]) -> str:
color = [i * 255 if i * 255 <= 255 else i * 255 - 1
for i in color[:-1]]
color = [int(round(i)) for i in color]
return "#xxx" % tuple(color)
def cmap_to_colors(cmap: str,
amount: int) -> List[str]:
cmap = mcm.get_cmap(cmap)
colors = [color_to_hex(cmap(i))
for i in np.linspace(0, 1, amount)]
return colors
def main() -> None:
df = read_to_df("age_dist_median_six.xlsx")
df_age_only = df.drop(["median", "youngest", "oldest"], axis = 1)
# transpose the dataframe
df_age_only = df_age_only.iloc[::-1]
# get a list of colors from cmap
colors = cmap_to_colors("viridis", 6)
barh = df_age_only.plot.barh(stacked = True, color = colors,
width = 0.95, xticks = np.linspace(0, 100, 11),
figsize = (10, 15))
barh.legend(bbox_to_anchor=(1, 1))
barh.margins(x = 0)
mpl.savefig("stacked_six_viridis.png")
if __name__ == "__main__":
main()
我通常對結果很滿意,但我也想突出顯示最大的條:所以我希望最大的(或那些,以防多個條的百分比最大)以實際顏色顯示,并顯示所有其他條灰色。我該怎么做?條形圖目前看起來像這樣:
用于圖表的 .xlsx 檔案可以在這里看到:
或者,如果您想保留原始顏色但突出顯示具有最大值的條,您可以通過改變 alpha 值來更改條的透明度。見下面的代碼:
import matplotlib.pyplot as mpl
import matplotlib.cm as mcm
import pandas as pd
import numpy as np
from typing import List, Tuple
def read_to_df(file_path: str) -> pd.DataFrame:
return pd.read_excel(file_path, index_col = 0)
def color_to_hex(color: Tuple[float]) -> str:
color = [i * 255 if i * 255 <= 255 else i * 255 - 1
for i in color[:-1]]
color = [int(round(i)) for i in color]
return "#xxx" % tuple(color)
def cmap_to_colors(cmap: str,
amount: int) -> List[str]:
cmap = mcm.get_cmap(cmap)
colors = [color_to_hex(cmap(i)) for i in np.linspace(0, 1, amount)]
return colors
def main() -> None:
df = read_to_df("age_dist_median_six.xlsx")
df_age_only = df.drop(["median", "youngest", "oldest"], axis = 1)
# transpose the dataframe
df_age_only = df_age_only.iloc[::-1]
colors = cmap_to_colors("viridis", 6)
fig=mpl.figure(figsize=(12,12))
N_teams=len(df_age_only)
for i in range(N_teams):
x_pos=0
for column,j in zip(df_age_only,range(len(colors))):
col_max=df_age_only.idxmax(axis='columns')[i]
if df_age_only[col_max][i]==df_age_only[column][i]:
if j==0:
mpl.barh(i,df_age_only[column][i],color=colors[j],align='center',edgecolor='tab:grey',alpha=1)
elif j>0:
mpl.barh(i,df_age_only[column][i],color=colors[j],left=x_pos,align='center',edgecolor='tab:grey',alpha=1)
else:
if j==0:
mpl.barh(i,df_age_only[column][i],color=colors[j],align='center',edgecolor='tab:grey',alpha=0.3)
elif j>0:
mpl.barh(i,df_age_only[column][i],color=colors[j],left=x_pos,align='center',edgecolor='tab:grey',alpha=0.3)
x_pos =df_age_only[column][i]
mpl.yticks(np.arange(N_teams),df_age_only.index,fontsize=9)
#Setting up legend:
for i in range(len(colors)):
mpl.plot([],[],color=colors[i],lw=10,label=str(df_age_only.keys()[i]))
mpl.legend()
mpl.show()
mpl.savefig("stacked_six_viridis.png")
if __name__ == "__main__":
main()
和輸出:

您可以更改以突出顯示條的其他內容包括edgecolor和hatch。
uj5u.com熱心網友回復:
一個想法是遍歷生成的條形,并更改它們的透明度。
下面的示例代碼plt用于使代碼更容易與教程和網路上的示例進行比較。另請注意,pandas 的繪圖函式通常回傳一個ax.
import matplotlib.pyplot as plt
from matplotlib.ticker import PercentFormatter
import pandas as pd
df = pd.read_excel("age_dist_median_six.xlsx", index_col=0)
df_age_only = df.drop(["median", "youngest", "oldest"], axis=1)
ax = df_age_only.plot.barh(cmap='viridis', stacked=True, edgecolor='black', width=1, clip_on=False, figsize=(12, 6))
ax.legend(bbox_to_anchor=(1.01, 1), loc='upper left')
ax.invert_yaxis()
ax.margins(x=0, y=0)
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.tick_params(axis='y', length=0)
ax.xaxis.set_major_formatter(PercentFormatter(100))
for i in range(len(df_age_only)):
max_val = np.nanmax(df_age_only.iloc[i].values)
for bar_group in ax.containers:
bar = bar_group[i]
if bar.get_width() < max_val - 1e-6:
bar.set_alpha(0.4)
# bar.set_facecolor('#DDDDDD') # light grey
plt.tight_layout()
plt.show()

轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/374532.html
標籤:Python 熊猫 matplotlib 可视化
