为了账号安全,请及时绑定邮箱和手机立即绑定

没有使用 Matplotlib Python 在后台获取热图

没有使用 Matplotlib Python 在后台获取热图

炎炎设计 2021-11-16 16:07:06
我试过这个并得到如图所示的结果:import pandas as pdimport matplotlib.pyplot as pltimport numpy as npfrom matplotlib.colors import LinearSegmentedColormapcmap = LinearSegmentedColormap.from_list("", ["red","grey","green"])df = pd.read_csv('t.csv', header=0)fig = plt.figure()ax1 = fig.add_subplot(111)ax = ax1.twiny()# Scatter plot of positive points, coloured blue (C0)ax.scatter(np.argwhere(df['real'] > 0), df.loc[df['real'] > 0, 'real'], color='C2')# Scatter plot of negative points, coloured red (C3)ax.scatter(np.argwhere(df['real'] < 0), df.loc[df['real'] < 0, 'real'], color='C3')# Scatter neutral values in grey (C7)ax.scatter(np.argwhere(df['real'] == 0), df.loc[df['real'] == 0, 'real'], color='C7')ax.set_ylim([df['real'].min(), df['real'].max()])index = len(df.index)ymin = df['prediction'].min()ymax= df['prediction'].max()ax1.imshow([np.arange(index),df['prediction']],cmap=cmap,                        extent=(0,index-1,ymin, ymax), alpha=0.8)plt.show()图片:我期待一个输出,其中根据图放置颜色。我得到绿色,没有红色或灰色。我想让图像或轮廓按值传播。我怎么能做到这一点?见下图,类似的东西:请让我知道我如何实现这一目标。我使用的数据在这里:t.csv对于实时版本,请查看Tensorflow Playground
查看完整描述

2 回答

?
德玛西亚99

TA贡献1770条经验 获得超3个赞

像这样的解决方案基本上需要 2 个任务:

  • 绘制热图作为背景;

  • 绘制散点数据;

输出

//img1.sycdn.imooc.com//619366df000159fd06200671.jpg

源代码:


import numpy as np

import matplotlib.pyplot as plt


###

# Plot heatmap in the background

###


# Setting up input values

x = np.arange(-6.0, 6.0, 0.1)

y = np.arange(-6.0, 6.0, 0.1)

X, Y = np.meshgrid(x, y)


# plot heatmap colorspace in the background

fig, ax = plt.subplots(nrows=1)

im = ax.imshow(X, cmap=plt.cm.get_cmap('RdBu'), extent=(-6, 6, -6, 6), interpolation='bilinear')

cax = fig.add_axes([0.21, 0.95, 0.6, 0.03]) # [left, bottom, width, height]

fig.colorbar(im, cax=cax, orientation='horizontal')  # add colorbar at the top


###

# Plot data as scatter

###

# generate the points

num_samples = 150

theta = np.linspace(0, 2 * np.pi, num_samples)


# generate inner points

circle_r = 2

r = circle_r * np.random.rand(num_samples)

inner_x, inner_y = r * np.cos(theta), r * np.sin(theta)


# generate outter points

circle_r = 4

r = circle_r + np.random.rand(num_samples)

outter_x, outter_y = r * np.cos(theta), r * np.sin(theta)


# plot data

ax.scatter(inner_x, inner_y, s=30, marker='o', color='royalblue', edgecolors='white', linewidths=0.8)

ax.scatter(outter_x, outter_y, s=30, marker='o', color='crimson', edgecolors='white', linewidths=0.8)

ax.set_ylim([-6,6])

ax.set_xlim([-6,6])


plt.show()

为了简单起见,我保留了颜色条范围(-6, 6)以匹配数据范围。


我确信可以更改此代码以满足您的特定需求。祝你好运!


查看完整回答
反对 回复 2021-11-16
?
阿晨1998

TA贡献2037条经验 获得超6个赞

这是一个可能的解决方案。

一些注意事项和问题:

  • 您的数据文件中的“预测”值是多少?它们似乎与“真实”列中的值无关。

  • 为什么要创建第二个轴?图中底部 X 轴代表什么?我删除了第二个轴并标记了剩余的轴(索引和实数)。

  • 当您对 Pandas DataFrame 进行切片时,索引会随之而来。您不需要创建单独的索引(代码中的 argwhere 和 arange(index))。我简化了代码的第一部分,其中生成了散点图。

import pandas as pd

import matplotlib.pyplot as plt

import numpy as np

from matplotlib.colors import LinearSegmentedColormap

cmap = LinearSegmentedColormap.from_list("", ["red","grey","green"])

df = pd.read_csv('t.csv', header=0)

print(df)


fig = plt.figure()

ax = fig.add_subplot(111)


# Data limits

xmin = 0

xmax = df.shape[0]

ymin = df['real'].min()

ymax = df['real'].max()


# Scatter plots

gt0 = df.loc[df['real'] > 0, 'real']

lt0 = df.loc[df['real'] < 0, 'real']

eq0 = df.loc[df['real'] == 0, 'real']

ax.scatter(gt0.index, gt0.values, edgecolor='white', color='C2')

ax.scatter(lt0.index, lt0.values, edgecolor='white', color='C3')

ax.scatter(eq0.index, eq0.values, edgecolor='white', color='C7')

ax.set_ylim((ymin, ymax))

ax.set_xlabel('index')

ax.set_ylabel('real')


# We want 0 to be in the middle of the colourbar, 

# because gray is defined as df['real'] == 0

if abs(ymax) > abs(ymin):

    lim = abs(ymax)

else:

    lim = abs(ymin)


# Create a gradient that runs from -lim to lim in N number of steps,

# where N is the number of colour steps in the cmap.

grad = np.arange(-lim, lim, 2*lim/cmap.N)


# Arrays plotted with imshow must be 2D arrays. In this case it will be

# 1 pixel wide and N pixels tall. Set the aspect ratio to auto so that

# each pixel is stretched out to the full width of the frame.

grad = np.expand_dims(grad, axis=1)

im = ax.imshow(grad, cmap=cmap, aspect='auto', alpha=1, origin='bottom',

               extent=(xmin, xmax, -lim, lim))

fig.colorbar(im, label='real')

plt.show()

这给出了以下结果:

//img1.sycdn.imooc.com//619366fb00010bb916171102.jpg

查看完整回答
反对 回复 2021-11-16
  • 2 回答
  • 0 关注
  • 234 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信