Неожиданный результат при одновременном использовании двух графиков matplotlib
Я использую matplotlib для построения графиков для моего веб-проекта. Есть две функции просмотра. Одна для круговой диаграммы, а другая для столбчатой. Я получаю желаемую диаграмму, вызывая каждую из них по очереди, но когда я попытался вызвать обе функции одновременно. Я получил неожиданный результат. Например, и гистограмма, и круговая диаграмма дают одинаковые цифры, или одна или обе диаграммы не завершены.
Я добавил свой код ниже.
view.py
from .utils import draw_piechart,draw_barchart
# # Pie Chart
def piechart(request):
products = Product.objects.all()
draw_piechart(products)
return render(request,'store/piechart.html')
def barchart(request):
draw_barchart()
return render(request,'store/barchart.html')
utils.py
import matplotlib
matplotlib.use('Agg')
from matplotlib import pyplot as plt
import numpy as np
# from random import random, randint
import random
# Pie Chart
def draw_piechart(products):
# Pie chart, where the slices will be ordered and plotted counter-clockwise:
# labels = 'Sale', 'Purchase', 'Test'
labels = []
for i in products:
if i.category not in labels:
labels.append(i.category)
sizes = [random.randint(10,30), random.randint(30,50)]
# explode = (0.1, 0) # only "explode" the 2nd slice (i.e. 'Hogs')
explode = None
fig1, ax1 = plt.subplots(1)
ax1.pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%',
shadow=True, startangle=90)
ax1.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle.
plt.savefig('media/piechart.png',dpi=100, transparent=True)
from matplotlib import pyplot as plt2
def draw_barchart():
labels = ['G1', 'G2', 'G3', 'G4', 'G5']
men_means = [20, 35, 30, 35, 27]
women_means = [25, 32, 34, 20, 25]
men_std = [2, 3, 4, 1, 2]
women_std = [3, 5, 2, 3, 3]
width = 0.35 # the width of the bars: can also be len(x) sequence
fig, ax = plt2.subplots()
ax.bar(labels, men_means, width, yerr=men_std, label='Men')
ax.bar(labels, women_means, width, yerr=women_std, bottom=men_means,
label='Women')
ax.set_ylabel('Scores')
ax.set_title('Scores by group and gender')
ax.legend()
plt2.savefig('media/barchart.png',dpi=100, transparent=True)
piechart.html
<h5>Top Selling Products</h5>
<hr/>
<img src="./media/piechart.png" />
barchart.html
<h5>Sales in this week</h5>
<hr/>
<img src="./media/barchart.png" />
main.html
<section class="do_sec_2">
<div id="top_category" class="top_category">
</div>
<div id="sales-barchart" class="sales-barchart">
<h5>Sales in this week</h5>
</div>
</section>
</div>
<script>
//function to load pie chart for top products
$(document).ready(function() {
$("#top_category").empty();
$('#top_category').load("{% url 'piechart' %} ",
function () {
// alert("Load was performed.");
});
// function for update barchart
$('#sales-barchart').empty();
$('#sales-barchart').load("{% url 'barchart' %} ",
function () {
// alert("Load was performed.");
});
});
</script>
Паттерны URL выглядят следующим образом,
urlpatterns = [
path('piechart',views.piechart,name='piechart'),
path('barchart',views.barchart,name='barchart'),
]