Python用matplotlib库制作散点图,有三列数据,如下所示,前两列数据分别作X轴、Y轴,剩余一列数据通过点的颜色渐变来表示不同的数据,在一开始,我将第三列数据(以列表形式)传递给scatte()的形参c引发报错,所以我也不知道该怎样办了。
from matplotlib.font_manager import FontProperties
import matplotlib.pyplot as plt
import matplotlib.pyplot as mp
import csv
import Functions
font = FontProperties(fname=r"c:\\windows\\fonts\\simsun.ttc")
plt.rcParams['font.family'] = ['sans-serif']
plt.rcParams['font.sans-serif'] = ['SimHei']
filename = '..\\节气与舌象.csv'
x_v = []
y_v = []
color_v = []
with open(filename, encoding='gbk') as file:
reader = csv.reader(file)
for row in reader:
x_v.append(row[0])
y_v.append(row[1])
color_v.append(row[2])
color = Functions.transform_list_to_numpy(color_v)
# mp.style.use('seaborn') 发生警告,并且错误显示
fig, ax = mp.subplots()
ax.scatter(x_v, y_v, c=color, cmap=mp.cm.Blues, s=10) # c=color, cmap=mp.cm.Blues
ax.set_title('节气与舌象', fontsize=15, fontproperties=font)
ax.set_ylabel('舌象', fontsize=1, fontproperties=font)
ax.set_xlabel('节气', fontsize=10, fontproperties=font)
ax.tick_params(axis='both', which='major', labelsize=5)
mp.show()
# mp.savefig('节气与舌象.png', bbox_inches='tight')'
x_v = []
y_v = []
color_v = []
with open(filename, encoding='gbk') as file:
reader = csv.reader(file)
for row in reader:
x_v.append(row[0])
y_v.append(row[1])
color_v.append(row[2])
color = Functions.transform_list_to_numpy(color_v)
# mp.style.use('seaborn') 发生警告,并且错误显示
fig, ax = mp.subplots()
ax.scatter(x_v, y_v, c=color, cmap=mp.cm.Blues, s=10) # c=color, cmap=mp.cm.Blues
ax.set_title('节气与舌象', fontsize=15, fontproperties=font)
ax.set_ylabel('舌象', fontsize=1, fontproperties=font)
ax.set_xlabel('节气', fontsize=10, fontproperties=font)
ax.tick_params(axis='both', which='major', labelsize=5)
mp.show()
# mp.savefig('节气与舌象.png', bbox_inches='tight')
相关文件:Functions.py
import numpy as np
def transform_list_to_numpy(list_val: list):
matrix = np.ndarray(list_val)
return matrix
注:图片中的文件只是数据样式示例
请各位指点!
根据参考资料和代码,可知使用scatter()函数绘制散点图时,c参数需要传递一个表示颜色的数组。在你的代码中使用的第三列数据colors是一个代表颜色渐变的数组,但是scatter()函数的c参数只接受表示颜色的字符串或数值,而不支持渐变数组。因此,需要对第三列数据进行处理,将其转换为表示颜色的字符串或数值。
一种解决方案是将颜色数据映射为固定的字符串或数值,可以使用线性映射的方法将colors中的数值映射到固定的范围内,再将映射后的结果传递给scatter()函数的c参数。下面是具体的解决方案和代码示例:
import matplotlib.pyplot as plt
import numpy as np
x = [1, 2, 3, 4, 5]
y = [10, 20, 30, 40, 50]
colors = [0.1, 0.3, 0.5, 0.7, 0.9] # 第三列数据,表示颜色渐变
color_range = np.linspace(0, 1, len(colors)) # 生成指定范围内的数值
c_values = np.interp(colors, color_range, (0, 1)) # 将颜色数据映射到0到1的范围内
plt.scatter(x, y, c=c_values)
plt.show()
通过将颜色数据映射为固定的字符串或数值,可以解决scatter()函数的c参数不能接受颜色渐变数组的问题。希望这个解决方案能帮助到你!如果还有其他问题,可以随时追问。