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

我试过这个并得到如图所示的结果:


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)


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()

图片:

http://img3.mukewang.com/619366be00013d9606210464.jpg

我期待一个输出,其中根据图放置颜色。我得到绿色,没有红色或灰色。

我想让图像或轮廓按值传播。我怎么能做到这一点?见下图,类似的东西:

http://img2.mukewang.com/619366ca0001278202680271.jpg

请让我知道我如何实现这一目标。我使用的数据在这里:t.csv
对于实时版本,请查看Tensorflow Playground

炎炎设计
浏览 235回答 2
2回答

德玛西亚99

像这样的解决方案基本上需要 2 个任务:绘制热图作为背景;绘制散点数据;输出:源代码:import numpy as npimport matplotlib.pyplot as plt#### Plot heatmap in the background#### Setting up input valuesx = 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 backgroundfig, 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')&nbsp; # add colorbar at the top#### Plot data as scatter#### generate the pointsnum_samples = 150theta = np.linspace(0, 2 * np.pi, num_samples)# generate inner pointscircle_r = 2r = circle_r * np.random.rand(num_samples)inner_x, inner_y = r * np.cos(theta), r * np.sin(theta)# generate outter pointscircle_r = 4r = circle_r + np.random.rand(num_samples)outter_x, outter_y = r * np.cos(theta), r * np.sin(theta)# plot dataax.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)以匹配数据范围。我确信可以更改此代码以满足您的特定需求。祝你好运!

阿晨1998

这是一个可能的解决方案。一些注意事项和问题:您的数据文件中的“预测”值是多少?它们似乎与“真实”列中的值无关。为什么要创建第二个轴?图中底部 X 轴代表什么?我删除了第二个轴并标记了剩余的轴(索引和实数)。当您对 Pandas DataFrame 进行切片时,索引会随之而来。您不需要创建单独的索引(代码中的 argwhere 和 arange(index))。我简化了代码的第一部分,其中生成了散点图。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)print(df)fig = plt.figure()ax = fig.add_subplot(111)# Data limitsxmin = 0xmax = df.shape[0]ymin = df['real'].min()ymax = df['real'].max()# Scatter plotsgt0 = 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,&nbsp;# because gray is defined as df['real'] == 0if abs(ymax) > abs(ymin):&nbsp; &nbsp; lim = abs(ymax)else:&nbsp; &nbsp; 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',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;extent=(xmin, xmax, -lim, lim))fig.colorbar(im, label='real')plt.show()这给出了以下结果:
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python