python - Using Matplotlib with Django -
i have built simple web application using django reads csv file , allows users plot graphs selecting x & y attributes.
the frontend makes use of ajax calls call backend methods plot graphs using python's matplotlib. issue arises when plots called asynchronously, causing race condition: different charts plotted same figure.
in attempts overcome problem, assign random "id" each user can call matplotlib figure number -- each user plots on different figures.
import matplotlib import pandas pd matplotlib.use('agg') #cm array containing 2 confusion matrices generated 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. 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)
however, not solve problem -- when user plots 3 graphs @ 1 time graphs overlap on each other.
ok, try plot directly axis create this:
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. 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)
Comments
Post a Comment