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

标签 python legend xlrd

我已经将一些数据从 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/

相关文章:

python - 使用 Google App Engine (Python) 的 PDF 缩略图

python列表转换为表格

javascript - 将鼠标悬停在 ApexCharts.js 中的图例系列上时如何显示图例工具提示

python - 使用 xlrd 迭代所有列

python-2.7 - 使用 Python 删除现有 Excel 工作表中的整个空白行

python - 在linux下从源码安装wxPython

Python rpy2 错误加载 edgeR R 包,但它已安装并在 R 中工作

java - JFreeChart:将图例嵌入箱线图中

plot - 如何在谷歌电子表格图中编辑图例标签?

Python - 循环遍历非空白 Excel 单元格