gpt4 book ai didi

python - 在 Python 中为散点图设置图例

转载 作者:行者123 更新时间:2023-12-04 03:39:32 24 4
gpt4 key购买 nike

我已经将一些数据从 excel 文件导入到 Python 中,我想做一个散点图。我遇到的问题是传说。我包括下面的代码:

data_2 = xlrd.open_workbook('/Users/.../.../Book1.xlsx')
sheet = data_2.sheet_by_index(0)
sheet.cell_value(0,0)
fig = plt.figure(figsize = (11,8), facecolor='white', edgecolor='black')
plt.xlabel('some x label')
plt.ylabel('some y label')
plt.xticks(np.arange(0.0, 30, 1.0))
plt.yticks(np.arange(-9.50, 1.0, 0.50))
plt.axhline(y=0.0, color='grey', linestyle=':')
plt.margins(0.01)
plt.savefig('plot.png')

for i in range(1, sheet.nrows):
xval = sheet.cell_value(i,0)
for j in range(1, sheet.ncols):
yval = sheet.cell_value(i,j)
plt.scatter(xval,yval, label = 'i = {}'.format(j))
plt.legend(loc='center left', bbox_to_anchor=(1, 0.5)) #the legend will appear on the right of the figure
虽然散点图很好,但图例条目重复了 31 次(31 是数据集中的列数)。我无法弄清楚是什么导致了问题。我尝试了 plt.legend(..) 行的不同位置,但没有成功。我曾尝试从头开始构建图例,但很难从图中提取点的颜色!如何修改代码以仅在右侧使用 sheet.ncols - 1(数据集中的第一列是 xaxis 值)条目输出图例?
如果有帮助,这是我使用 Excel 绘制数据时得到的图表(但我不想使用 Excel 绘制图表)
enter image description here
我希望代码在 python 中重现这样的情节。请注意,图例位置在底部,但最好将其放在图的右侧

最佳答案

尝试只标记一行的条目,例如 plt.scatter(xval,yval, label = 'i = {}'.format(j) if i==1 else None) 。无论标签的内容如何,​​Matplotlib 都会为图中的每个标记对象自动创建一个图例条目。

关于python - 在 Python 中为散点图设置图例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66308587/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com