在学习Matplotlib时,我编辑了以下代码:
import matplotlib.pyplot as plt
input_values = [1,2,3,4,5,6,7,8,9,10]
plt.style.use('seaborn')
fig,ax = plt.subplots()
squares = []
for square in input_values:
squarea = square**2
squares.append(squarea)
ax.plot(input_values,squares,linewidth = 5) #linewidth自定义线的宽度
#设置图标标题,并给坐标轴加上标签
ax.set_title("Square Numbers",fontsize = 24)
ax.set_xlabel("Value",fontsize = 14)
ax.set_ylabel("Square of Value",fontsize = 14)
#设置刻度标记的大小
ax.tick_params(axis = 'both',labelsize = 14)
plt.show()
在运行后,Pycharm提示使用其内置样式“plt.style.use(‘seaborn’)”时出现以下错误:
OSError: ‘seaborn’ is not a valid package style, path of style file, URL of style file, or library style name (library styles are listed in style.available
)
要解决这个问题其实很简单,我们可以通过通过 plt.style.available 查看目前所有可用的样式表:
import matplotlib.pyplot as plt
# 获取所有可用的样式表名称
available_styles = plt.style.available
# 打印样式表名称
for style in available_styles:
print(style)
# 或者,如果你只是想查看列表而不是遍历它,你可以直接打印 available_styles
# print(available_styles)
或者
import matplotlib.pyplot as plt
print(plt.style.available)
遍历出来的结果如下:
Solarize_Light2
_classic_test_patch
_mpl-gallery
_mpl-gallery-nogrid
bmh
classic
dark_background
fast
fivethirtyeight
ggplot
grayscale
seaborn-v0_8
seaborn-v0_8-bright
seaborn-v0_8-colorblind
seaborn-v0_8-dark
seaborn-v0_8-dark-palette
seaborn-v0_8-darkgrid
seaborn-v0_8-deep
seaborn-v0_8-muted
seaborn-v0_8-notebook
seaborn-v0_8-paper
seaborn-v0_8-pastel
seaborn-v0_8-poster
seaborn-v0_8-talk
seaborn-v0_8-ticks
seaborn-v0_8-white
seaborn-v0_8-whitegrid
tableau-colorblind10
可以看到,由于Seaborn库的变动,我们可以将“seaborn”更换成“seaborn-v0_8”即可正常运行。
修改后的代码如下:
import matplotlib.pyplot as plt
input_values = [1,2,3,4,5,6,7,8,9,10]
plt.style.use('seaborn-v0_8')
fig,ax = plt.subplots()
squares = []
for square in input_values:
squarea = square**2
squares.append(squarea)
ax.plot(input_values,squares,linewidth = 5) #linewidth 这里意思是自定义线的宽度
#设置图标标题,并给坐标轴加上标签
ax.set_title("Square Numbers",fontsize = 24)
ax.set_xlabel("Value",fontsize = 14)
ax.set_ylabel("Square of Value",fontsize = 14)
#设置刻度标记的大小
ax.tick_params(axis = 'both',labelsize = 14)
plt.show()
运行后,就可以得到以下图像啦: