I am trying to create a dashboard where I can analyse my model's data (Article) using the library plotly .
The Plotly bar chart is not showing on my template, I am wondering if I am doing something wrong since there's no error with the code below :
models.py
from django.db import models
from django.contrib.auth.models import User
import plotly.plotly as py
import plotly.graph_objs as go
class Article(models.Model):
user = models.ForeignKey(User, default='1')
titre = models.CharField(max_length=100, unique=True)
slug = models.SlugField(max_length=40)
likes = models.ManyToManyField(User, related_name="likes")
def __str__(self):
return self.titre
@property
def article_chart(self):
data = [
go.Bar(
x=[self.titre], #title of the article
y=[self.likes.count()] #number of likes on an article
)
]
plot_url = py.plot(data, filename='basic-bar')
return plot_url
dashboard.html
<div>{{ article.article_chart }}</div>
Why is the bar chart not visible? Any suggestion ?
The result of
py.plot(data, filename='basic-bar')
is to generate a offline HTML file and return a local URL of this file
eg file:///your_project_pwd/temp-plot.html
If you want to render it in Django framework, you need to
<iframe>
and restructure of your folder in Django settings OR
data
There is a example which I had tried:
figure_or_data = [Scatter(x=[1, 2, 3], y=[3, 1, 6])]
plot_html = plot_html, plotdivid, width, height = _plot_html(
figure_or_data, True, 'test', True,
'100%', '100%')
resize_script = ''
if width == '100%' or height == '100%':
resize_script = (
''
'<script type="text/javascript">'
'window.removeEventListener("resize");'
'window.addEventListener("resize", function(){{'
'Plotly.Plots.resize(document.getElementById("{id}"));}});'
'</script>'
).format(id=plotdivid)
html = ''.join([
plot_html,
resize_script])
return render(request, 'dashboard.html', {'html': html,})
The above answer was very useful, I am in fact watching for parent resize, I am working in angular and I used the below code to achieve the resize, I am having a similar problem and this line of code was useful
<div class="col-lg-12" ng-if="showME" style="padding:0px">
<div id="graphPlot" ng-bind-html="myHTML"></div>
</div>
The graph will be inserted through the variable myHTML
All i did was watch for the parent resize and got the div id alone using jquery and passed it to plotly and it worked.
$scope.$on("angular-resizable.resizeEnd", function (event, args){
Plotly.Plots.resize(document.getElementById($('#graphPlot').children().eq(0).attr("id")));
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.