Seaborn绘图问题:隐藏多余文本及解决设置不生效问题
问题描述
我是Seaborn新手,正在课堂作业中使用VSCode编辑Notebook,遇到两个问题:
- 执行barplot代码后,VSCode输出的图表带有多余文本,请问如何隐藏该文本?代码:
myPlot = sns.barplot(dfFrequencies, x="Topic", y="Relative Frequency") myPlot.set_xticklabels(myPlot.get_xticklabels(), rotation=45) myPlot.set_title("Pew Poll Responses: Which is Most Meaningful?")
- 执行scatterplot代码时,设置标题、坐标轴标签的操作未生效,且图表仍有多余文本,请问问题出在哪里?代码:
sns.set(rc={"figure.figsize":(10, 6)}) set_style(theme) myplot = sns.scatterplot(data=dfHofData, x="Midpoint", y="OPS_z") myPlot.set_title("Standardized OPS by Mid-Career Year") myPlot.set_xlabel("Mid-Career Year") myPlot.set_ylabel("Standardized On Base Percentage Plus Slugging (OPS)")
注:set_style为讲师提供的深色主题设置函数,代码如下:
theme = 'darkmode' def set_style(theme='darkmode'): if theme == 'darkmode': sns.set_theme(style='ticks', context='notebook', rc={'axes.facecolor':'black', 'figure.facecolor':'black', 'text.color':'white', 'xtick.color':'white', 'ytick.color':'white', 'axes.labelcolor':'white', 'axes.grid':False, 'axes.edgecolor':'white'}) else: sns.set_theme(style='ticks', context='notebook')
解决方案
问题1:Barplot 多余文本隐藏
原因
VSCode Notebook会自动输出代码单元格最后一个对象的字符串表示(此处为Matplotlib的Axes对象),也就是你看到的多余文本。
解决方法
在代码块最后一行末尾添加;,或者调用matplotlib.pyplot.show(),即可抑制该对象输出:
方法1:添加分号
import matplotlib.pyplot as plt # 若未导入需先添加 myPlot = sns.barplot(dfFrequencies, x="Topic", y="Relative Frequency") myPlot.set_xticklabels(myPlot.get_xticklabels(), rotation=45) myPlot.set_title("Pew Poll Responses: Which is Most Meaningful?"); # 末尾加分号
方法2:调用plt.show()
import matplotlib.pyplot as plt myPlot = sns.barplot(dfFrequencies, x="Topic", y="Relative Frequency") myPlot.set_xticklabels(myPlot.get_xticklabels(), rotation=45) myPlot.set_title("Pew Poll Responses: Which is Most Meaningful?") plt.show()
问题2:Scatterplot 标题/轴标签不生效 + 多余文本
原因
- 变量名大小写不一致:散点图对象被赋值给
myplot(小写p),但后续调用set_title()等方法时用的是myPlot(大写P),Python对大小写敏感,导致操作的是之前条形图的对象,而非当前散点图。 - 多余文本的原因与问题1相同,是Axes对象的默认输出。
解决方法
统一变量名,同时添加抑制对象输出的方式:
修改后的代码:
import matplotlib.pyplot as plt sns.set(rc={"figure.figsize":(10, 6)}) set_style(theme) myPlot = sns.scatterplot(data=dfHofData, x="Midpoint", y="OPS_z") # 统一为大写P的myPlot myPlot.set_title("Standardized OPS by Mid-Career Year") myPlot.set_xlabel("Mid-Career Year") myPlot.set_ylabel("Standardized On Base Percentage Plus Slugging (OPS)"); # 末尾加分号
或用plt.show()替代分号:
import matplotlib.pyplot as plt sns.set(rc={"figure.figsize":(10, 6)}) set_style(theme) myPlot = sns.scatterplot(data=dfHofData, x="Midpoint", y="OPS_z") myPlot.set_title("Standardized OPS by Mid-Career Year") myPlot.set_xlabel("Mid-Career Year") myPlot.set_ylabel("Standardized On Base Percentage Plus Slugging (OPS)") plt.show()
内容的提问来源于stack exchange,提问作者jerH
相关产品推荐
相关产品推荐

