python词云图代码

python词云图无法显示中文

import pandas as pd
from collections import Counter
from wordcloud import WordCloud
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
plt.rcParams['font.family'] = ['sans-serif']
plt.rcParams['font.sans-serif'] = ['SimHei']
keywords = []
for desc in df['type']:
    words = desc.split()
    keywords.extend(words)
keyword_counts = Counter(keywords)
wordcloud = WordCloud(width=400, height=200).generate_from_frequencies(keyword_counts)
plt.figure(figsize=(10, 5))
plt.imshow(wordcloud, interpolation='bilinear',)
plt.axis('off')
plt.show()

你遇到的问题可能是因为Matplotlib使用的字体不支持中文字符。Matplotlib使用不同的字体管理器来处理字体渲染,有时默认字体可能没有必要的字符。

为了解决这个问题,你可以尝试以下步骤:

  1. 如果你还没有安装支持中文字符的字体,请在系统上安装一个。一个常用的选择是"SimHei"字体。
  2. 在Matplotlib中指定字体属性,以使用支持中文字符的字体。你可以通过将font.sans-serif属性设置为字体名称来实现。
    下面是更新后的代码示例,调整了字体设置:
import pandas as pd
from collections import Counter
from wordcloud import WordCloud
import matplotlib.pyplot as plt

# 设置字体属性以支持中文字符
plt.rcParams['font.sans-serif'] = ['SimHei']

keywords = []
for desc in df['type']:
    words = desc.split()
    keywords.extend(words)

keyword_counts = Counter(keywords)
wordcloud = WordCloud(width=400, height=200).generate_from_frequencies(keyword_counts)

plt.figure(figsize=(10, 5))
plt.imshow(wordcloud, interpolation='bilinear')
plt.axis('off')
plt.show()

通过设置plt.rcParams['font.sans-serif'] = ['SimHei'],你告诉Matplotlib使用"SimHei"字体来渲染中文字符。如果你安装了其他字体,请确保用相应的字体名称替换'SimHei'。

确保你的系统上安装了必要的字体,代码应该能够显示词云图中的中文字符。