基于差分的x、y标题、图例绘制散点图

2024-09-30 01:25:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我从网上找了一些代码,找到了下面的函数,让我根据第三列的值绘制。比如result=0黄色,result=1,color=紫色。 但xlabel、ylabel、title或legend即使我添加也不显示ax.set U标题, 轴设置标签, 轴套, 斧头图例. 在

我怎样才能描绘出像“随机行走者”图像“蓝线”代表平均人口1,“黄线”代表男性人口2 结果=1,黄色 结果=0,紫色

def plot_scatter(df=tmp, xcol='freq', ycol='type', catcol='result'):
    fig, ax = plt.subplots()
    categories = np.unique(df[catcol])
    colors = np.linspace(0, 1, len(categories))
    colordict = dict(zip(categories, colors))

    df["Color"] = df[catcol].apply(lambda x: colordict[x])
    ax.set_title('random walkers empirical $\mu$ and $\pm \sigma$ interval')
    ax.legend(loc='best')
    ax.set_xlabel(xcol)
    ax.set_ylabel(ycol)
    ax.scatter(df[xcol], df[ycol], c=df.Color)
    return fig

fig = plot_scatter(tmp)
fig.show()

plot result

enter image description here


Tags: dftitlefigresultaxcategoriesset黄色
1条回答
网友
1楼 · 发布于 2024-09-30 01:25:43

修改答案:

下面是一个示例代码,它可以执行我认为您想做的事情,但是没有数据帧,因为我没有您的数据帧:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches

fig, ax = plt.subplots()

# this part should get replaced with your dataframe-based calculations
x = np.linspace(0, 1, 100)
y = np.random.randint(0, 2, 100)
colordict = {0: 'yellow', 1: 'purple'}
color = list(colordict[val] for val in y)

ax.scatter(x, y, c = color, label = color)

ax.set_title('random walkers empirical $\mu$ and $\pm \sigma$ interval')
ax.set_xlabel('freq')
ax.set_ylabel('type')

# custom patches for the legend
yellow_patch = mpatches.Patch(color='yellow', label='population 1, result = 0')
purple_patch = mpatches.Patch(color='purple', label='population 2, result = 1')
ax.legend(handles=[yellow_patch, purple_patch])

plt.show()

不幸的是,我之前的答案(保留在下面)并没有真正解决问题,因为我不理解我链接的示例。您要做的是定制标签,这更像this example。在

至于注释中的代码,请注意,您需要在所有要包含其标签的绘图命令之后调用legend。我不知道为什么你的坐标轴标签和标题没有出现-当我运行我的版本的时候。在


不幸的是,下面这些并不能真正解决问题。在

图例未出现,因为绘图中没有任何元素有标签。您没有提供足够的代码来复制绘图,但是this example表示您应该能够将label = df.Color传递给scatter以获得正确的效果。所以您对scatter的调用看起来像:

^{pr2}$

相关问题 更多 >

    热门问题