Matplotlib坐标轴未显示问题求助:如何添加散点图坐标轴标签
解决Matplotlib散点图坐标轴标签不显示的问题
嘿,你的代码里坐标轴标签没显示的原因很简单——你写错了设置标签的方式!
你现在是把plt.xlabel和plt.ylabel当成变量来赋值了(用了=),但实际上它们是Matplotlib的方法,得用括号调用才能生效。
修正后的完整代码:
import matplotlib.pyplot as plt import pandas as pd import pylab as pl import numpy as np %matplotlib inline !wget -O FuelConsumption.csv https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/ML0101ENv3/labs/FuelConsumptionCo2.csv df = pd.read_csv("FuelConsumption.csv") df.head() df1 = df[['ENGINESIZE','CYLINDERS','FUELCONSUMPTION_COMB','CO2EMISSIONS']] df1.head(9) plt.scatter(df1.ENGINESIZE , df1.CO2EMISSIONS , color = "black") # 这里改成方法调用,去掉等号 plt.xlabel("enginesize") plt.ylabel("emission") plt.show()
错误点解释:
原来的代码里:
plt.xlabel=("enginesize") plt.ylabel=("emission")
这两行是把字符串赋值给了plt.xlabel这个方法对象,相当于覆盖了原本的方法,根本没有触发设置标签的逻辑。而正确的写法是调用方法并传入标签文本:plt.xlabel("enginesize"),这样Matplotlib才会把标签渲染到坐标轴上。
如果想要让标签更醒目,还可以额外传入参数调整样式,比如:
plt.xlabel("enginesize", fontsize=12, fontweight='bold') plt.ylabel("emission", fontsize=12, fontweight='bold')
内容的提问来源于stack exchange,提问作者vish
相关产品推荐
相关产品推荐

