File size: 3,675 Bytes
332ef47 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 | import matplotlib.pyplot as plt
import numpy as np
import matplotlib.animation as animation
from matplotlib.patches import Patch
from matplotlib.patheffects import withStroke
from matplotlib.colors import LinearSegmentedColormap
# 设置中文和 emoji 字体兼容
plt.rcParams["font.family"] = ["Microsoft YaHei", "Segoe UI Emoji"]
plt.rcParams["axes.unicode_minus"] = False
emoji_map = {
"joy": "😊", "contentment": "😌", "pride": "😼", "anger": "😠", "annoyance": "😒",
"sadness": "😢", "regret": "😔", "loneliness": "🥺", "fear": "😱", "anxiety": "😰",
"shame": "😳", "surprise": "😲", "shock": "😵", "love": "😍", "attachment": "🤗",
"neutral": "😶"
}
def plot_emotions(data, visual_styles=None, output_file=None):
sorted_items = sorted(data.items(), key=lambda x: x[1], reverse=True)
emotions = [k for k, v in sorted_items]
percentages = [v for k, v in sorted_items]
values = [v / 100 for v in percentages]
x = np.arange(len(emotions))
width = 0.6
base_colors = []
if visual_styles:
base_colors = [visual_styles.get(e, {}).get("color", "#D8BFD8") for e in emotions]
else:
base_colors = ["#D8BFD8"] * len(emotions)
fig, ax = plt.subplots(figsize=(10, 6))
fig.patch.set_facecolor('#FFF0F5')
ax.set_facecolor("#FFF8FC")
ax.set_title("情绪分布图 (。♥‿♥。)", fontsize=20, fontweight='bold', pad=15, color="#C71585")
ax.set_xlabel("情绪类别", fontsize=14, labelpad=10, color="#8B008B")
ax.set_ylabel("占比", fontsize=14, labelpad=10, color="#8B008B")
bars = ax.bar(x, [0]*len(values), width, color=base_colors, edgecolor='white', linewidth=1.5)
ax.set_ylim(0, max(values) * 1.4 if values else 1)
ax.set_xticks(x)
ax.set_xticklabels(emotions, fontsize=12, rotation=30, color="#4B0082")
ax.set_yticks(np.linspace(0, 1, 6))
ax.set_yticklabels([f"{int(tick * 100)}%" for tick in np.linspace(0, 1, 6)], fontsize=12, color="#4B0082")
for spine in ax.spines.values():
spine.set_visible(False)
ax.grid(axis='y', color='#FFDDEE', linestyle='--', linewidth=0.5)
if visual_styles:
legend_elements = [
Patch(facecolor=visual_styles.get(e, {}).get("color", "#D8BFD8"), label=e)
for e in emotions
]
ax.legend(handles=legend_elements, title="情绪类别", loc="upper right",
fontsize=11, title_fontsize=12, frameon=True, edgecolor="#C71585",
facecolor="#FFE4F5", fancybox=True)
text_labels = []
emojis = []
for i, (bar, pct, emo) in enumerate(zip(bars, percentages, emotions)):
t = ax.text(bar.get_x() + bar.get_width()/2, 0, f"{pct:.2f}%", ha='center', va='bottom',
fontsize=10, fontweight='bold', color="#C71585",
path_effects=[withStroke(linewidth=2, foreground="white")])
text_labels.append(t)
emoj = ax.text(bar.get_x() + bar.get_width()/2, 0, emoji_map.get(emo, "😺"),
ha='center', fontsize=22)
emojis.append(emoj)
def update(frame):
for i, bar in enumerate(bars):
target = values[i]
bar.set_height(min(frame/30, target))
text_labels[i].set_y(min(frame/30, target) + 0.03)
emojis[i].set_y(min(frame/30, target) + 0.08)
return list(bars) + text_labels + emojis # ✅ 修复 concat 错误
ani = animation.FuncAnimation(fig, update, frames=31, interval=30, blit=True, repeat=False)
plt.tight_layout()
if output_file:
plt.savefig(output_file, bbox_inches='tight', dpi=120)
else:
plt.show()
|