gpt4 book ai didi

python - 将 Matplotlib 与 Django 结合使用

转载 作者:太空宇宙 更新时间:2023-11-03 14:52:49 24 4
gpt4 key购买 nike

我使用 Django 构建了一个简单的 Web 应用程序,该应用程序读取 csv 文件并允许用户通过选择 X 和 Y 属性来绘制图表。

前端利用 AJAX 调用来调用后端方法,以使用 Python 的 Matplotlib 绘制图形。当异步调用绘图时,就会出现问题,从而导致竞争条件:不同的图表绘制到同一个图形。

为了尝试克服这个问题,我为每个用户分配随机“id”,以便我可以调用 matplotlib 来获取图形编号 - 因此每个用户都会在不同的图形上绘制。

import matplotlib
import pandas as pd
matplotlib.use('agg')

#cm is an array containing 2 confusion matrices generated from http://scikit-learn.org/stable/modules/generated/sklearn.metrics.confusion_matrix.html
def plot_confusion_matrix(user_id, cm, classes, path,
normalize=False,
title='Confusion Matrix',
cmap=plt.cm.Blues):
id = user_id + random.randint(1, 10000)
fig = plt.figure(id)
axis1 = fig.add_subplot(121)
title1 = title + " (train)"
title2 =title + " (test)"
def plot_cm(cm, title):
plt.imshow(cm, interpolation='nearest', cmap=cmap)
plt.title(title)
#plt.colorbar()
tick_marks = np.arange(len(classes))
plt.xticks(tick_marks, classes, rotation=45)
plt.yticks(tick_marks, classes)
thresh = cm.max() / 2.
for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
plt.text(j, i, cm[i, j],
horizontalalignment="center",
color="white" if cm[i, j] > thresh else "black")

plt.tight_layout()
plt.ylabel('True label')
plt.xlabel('Predicted label')
plot_cm(cm=cm[0], title=title1)
axis2 = fig.add_subplot(122)
plot_cm(cm=cm[1], title=title2)
plt.tight_layout()
fig.savefig(path)
plt.close(id)

但是,这并不能解决问题——当用户一次绘制 3 个图表时,这些图表会相互重叠。

最佳答案

好的,尝试直接绘制到您创建的轴上,如下所示:

def plot_confusion_matrix(user_id, cm, classes, path,
normalize=False,
title='Confusion Matrix',
cmap=plt.cm.Blues):
id = user_id + random.randint(1, 10000)
fig = plt.figure(id)
axis1 = fig.add_subplot(121)
title1 = title + " (train)"
title2 =title + " (test)"
def plot_cm(cm, title, ax):
ax.imshow(cm, interpolation='nearest', cmap=cmap)
ax.set_title(title)
#plt.colorbar()
tick_marks = np.arange(len(classes))
ax.set_xticks(tick_marks, classes, rotation=45)
ax.set_yticks(tick_marks, classes)
thresh = cm.max() / 2.
for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
ax.text(j, i, cm[i, j],
horizontalalignment="center",
color="white" if cm[i, j] > thresh else "black")

plt.tight_layout()
ax.set_ylabel('True label')
ax.set_xlabel('Predicted label')
plot_cm(cm=cm[0], title=title1, axis1)
axis2 = fig.add_subplot(122)
plot_cm(cm=cm[1], title=title2, axis2)
plt.tight_layout()
plt.savefig(path)
plt.close(id)

关于python - 将 Matplotlib 与 Django 结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45789714/

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