导入CSV后Seaborn catplot不显示柱状图的问题排查
问题:导入CSV后Seaborn catplot不显示柱状图?
正常运行的代码示例
import matplotlib.pyplot as plt import seaborn as sns import pandas as pd # Change the color palette to "RdBu" par_ad = { "Parents advice":[1,2,3,3,4,5,4,3,1,1,1,1,1,2,3,5,2,1,3,4] } df = pd.DataFrame(par_ad) sns.set_style("whitegrid") sns.set_palette("RdBu") # Create a count plot of survey responses sns.catplot(x="Parents advice", data=df, kind="count") # Show plot plt.show()
导入CSV后无柱状图显示的代码
import seaborn as sns import pandas as pd # Change the color palette to "RdBu" survey_data = pd.read_csv("young-people-survey-responses.csv") sns.set_style("whitegrid") sns.set_palette("RdBu") # Create a count plot of survey responses category_order = ["Never", "Rarely", "Sometimes", "Often", "Always"] sns.catplot(x="Parents' advice", data=survey_data, kind="count", order=category_order) # Show plot plt.show()
原因分析
核心问题是数据类型与自定义类别不匹配:
- CSV文件中"Parents' advice"列存储的是1-5的整数,代表求助频率
- 代码中设置的
category_order是字符串标签("Never"等),Seaborn在数据中找不到与这些字符串匹配的类别值,因此无法生成对应的柱状图,且不会抛出报错(因为程序逻辑本身无语法错误,只是没有匹配的数据项)
解决方案
方案1:调整order参数为整数列表
直接使用数据中实际存在的整数值作为类别顺序:
category_order = [1, 2, 3, 4, 5] sns.catplot(x="Parents' advice", data=survey_data, kind="count", order=category_order) plt.show()
方案2:将数据中的整数映射为对应字符串标签
先把CSV中的整数转换成对应的文本标签,再使用原有的category_order:
# 定义整数到文本标签的映射 advice_mapping = { 1: "Never", 2: "Rarely", 3: "Sometimes", 4: "Often", 5: "Always" } # 替换列中的值 survey_data["Parents' advice"] = survey_data["Parents' advice"].map(advice_mapping) # 再执行绘图代码 category_order = ["Never", "Rarely", "Sometimes", "Often", "Always"] sns.catplot(x="Parents' advice", data=survey_data, kind="count", order=category_order) plt.show()
验证步骤(可选)
可以先打印数据列的唯一值,确认数据实际内容:
print(survey_data["Parents' advice"].unique())
内容的提问来源于stack exchange,提问作者Manuel Veiga
相关产品推荐
相关产品推荐

