[Python]-plt.style.use(‘seaborn‘)报错


在学习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()

运行后,就可以得到以下图像啦:
在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值