Chart JS only showing first 2 values - python

I'm using this for my chart application right now
<script>
var canvas = document.getElementById('myChart');
new Chart(document.getElementById("myCanvas"), {
type: 'line',
data: {
labels: mon_unique,
datasets: [{
data: values,
borderColor: "#3e95cd",
fill: false
},
]
},
options: {
title: {
display: true,
},
hover: {
mode: 'index',
intersect: true
},
}
});
</script>
values, what I called my data in my flask app, is a list of numbers. When I change data: [0,1,2,3,4] it graphs it, but it doesn't pass in my values at all.
data = remove_err_str
return render_template('graphing.html', values=data)
This displays only the first two points in values. Values is a list of about 50,000 items. It looks like ['1243.42','2`,...]
<body>
<canvas id="myChart" width="400" height="400"></canvas>
<script>
var canvas = document.getElementById('myChart');
new Chart(document.getElementById("myChart"), {
type: 'line',
data: {
datasets: [{
data: {{values | safe}},
borderColor: "#3e95cd",
fill: false
},
]
},
options: {
title: {
display: true,
test: "Chart for the sweep data"
},
hover: {
mode: 'index',
intersect: true
},
}
});
</script>
</body>

This is the solution I found
Graphing HTML page
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.0.0/Chart.bundle.js"></script>
</head>
<body>
<canvas id="myChart" width="1600" height="800"></canvas>
<script>
var canvas = document.getElementById('myChart');
var chart = new Chart(canvas, {
type: 'line',
data: {
labels: {{ labels | safe }},
datasets: [{
label: "Line chart for sweep data",
data: {{ values | safe }},
fill: false
}]
},
options: {
responsive: false,
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}}}
);
</script>
Every item needs a label. If it gets passed in without a label it won't graph. Also I changed the 'beginAtZero' to be set to true, otherwise it starts the lowest y value in the list. To create labels for every value I did this in my flask app.py
for i in data: #turns it from a list of string values to float values
float_data.append(float(i))
count = count + 1
label_arr.append(count)
return render_template('graphing.html', values=float_data, labels=label_arr)
:*]

You are passing data from python-end to front-end so you have to use jinja template inside your code and for that double-brackets can be used
<script>
var canvas = document.getElementById('myChart');
new Chart(document.getElementById("myCanvas"), {
type: 'line',
data: {
labels: mon_unique,
datasets: [{
data: {{values | tojson}},
borderColor: "#3e95cd",
fill: false
},
]
},
options: {
title: {
display: true,
},
hover: {
mode: 'index',
intersect: true
},
}
});
</script>

Related

Highcharts. Django won't load. Highcharts with Django

There is a wonderful library of js - Highcharts. I'm trying to link it to Django, and everything actually works, but not when I'm trying to insert a variable with content into data. Here's the code.
This function returns what I substitute in data in Highcharts.
def get_series(context):
data_ser = []
for i in context:
if i in ['One', "Two", "Three", "Four", "Five"]:
data_ser.append({
'name': i,
'y': context[i],
'z': 22.2
})
data_ser = json.dumps(data_ser)
return data_ser
And this is the jquery code itself:
<script>
$(document).ready(function () {
var data_ser = '{{ data_ser|safe }}'
console.log(data_ser)
Highcharts.chart('container', {
chart: {
type: 'variablepie'
},
title: {
text: 'Stats'
},
series: [{
minPointSize: 10,
innerSize: '20%',
zMin: 0,
name: 'countries',
data: data_ser
}]
});
})
</script>
In series in data, I try to substitute data_ser, but the graph is not output. Although, if you write it manually, then everything will work.
Similar code works:
<script>
$(document).ready(function () {
var data_ser = '{{ data_ser|safe }}'
console.log(data_ser)
Highcharts.chart('container', {
chart: {
type: 'variablepie'
},
title: {
text: 'Stats'
},
series: [{
minPointSize: 10,
innerSize: '20%',
zMin: 0,
name: 'countries',
data: [
{
"name": "One",
"y": 50.0,
"z": 22.2
}]
}]
});
})
</script>
I really hope for help. Or give at least alternative js libraries with graphs where this will work.
It looks like the issue is that data_ser is a string that represents a JavaScript object, but it is being treated as a string in the data property of the series object.
Try it with:
<script>
...
var data_ser = JSON.parse('{{ data_ser|safe }}')
...
</script>

Chart js space above bar graph

I generate graph depending on the value from my calculations. Problem is, I don't know how to set up 'margins', how to define where to put data labels.
Datalables definition:
datalabels: {
anchor: 'end',
align: 'start',
offset: 5,
Problem is, when a certain month value is 0, it's written over the labels on the bottom. Easy way to fix this would be to define a space about each column, so that it can that text can never go 'off screen' and define align: 'end'.
Case 2:
You could define some extra padding at the top of your chart using the option layout.padding.top.
Please take a look at below runnable code and see how it works:
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
plugins: [ChartDataLabels],
data: {
labels: ['A', 'B', 'C'],
datasets: [{
label: 'My Dataset',
data: [0, 0, 3],
backgroundColor: 'orange'
}
]
},
options: {
layout: {
padding: {
top: 30
}
},
plugins: {
legend: {
display: false
},
datalabels: {
align: 'end',
anchor: 'end'
}
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.2.0/chart.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-datalabels/2.0.0-rc.1/chartjs-plugin-datalabels.min.js"></script>
<canvas id="myChart" height="120"></canvas>

Error trying to switch between different charts

I am developing an application which shows the data created in a chartjs graph, what I am doing it does well, since all the data is displayed in the way I want, but I have a problem and that is that now I am trying to do that according to the type of graph that a user wants this to be changed, the problem is that the graph is changed but in case of having multiple graphs only the first graph is changed, the others continue with the graph by default, this is my template:
<select name="chartType" id="chartType" onchange="updateChart()" data-role="select">
<option value="pie">pie</option>
<option value="bar">Bar</option>
</select>
<canvas id="{{ project.slug }}" width="400" height="400"></canvas>
This is my script:
var faltante = 100 - {{ project.porcent }};
var data = {
labels: ['{{ project.name }}', 'Falta'],
datasets: [{
data: [{{ project.porcent }}, faltante],
backgroundColor: ['#252850', '#f44611']
}],
};
var ctx = document.getElementById('{{ project.slug }}').getContext('2d');
var myChart = new Chart(ctx, {
type: 'pie',
data: data
});
function updateChart() {
myChart.destroy();
myChart = new Chart(ctx, {
type: document.getElementById("chartType").value,
data: data
});
}
You can invoke your updateChart function with the selected chart type as follows:
onchange="updateChart(this.value)"
Everything could then be done inside the updateChart function.
destroy the chart if it already exists
create the new chart with the specified type
To make this work, you'll also have to explicitly invoke updateChart once with the initial chart type.
updateChart('pie');
Please take a look at below runnable code snippet and see how it works.
let myChart;
function updateChart(type) {
if (myChart) {
myChart.destroy();
}
myChart = new Chart('chart', {
type: type,
data: {
labels: ['A', 'B'],
datasets: [{
data: [3, 6],
backgroundColor: ['#252850', '#f44611']
}]
},
options: {
scales: {
yAxes: [{
display: type == 'bar',
ticks: {
beginAtZero: true
}
}]
}
}
});
}
updateChart('pie');
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js"></script>
<select name="chartType" id="chartType" onchange="updateChart(this.value)" data-role="select">
<option value="pie">Pie</option>
<option value="bar">Bar</option>
</select>
<canvas id="chart" height="100"></canvas>

react-table not rendering server-side data in table (with manual pagination, filtering & sorting)

I'm having trouble getting data from the backend (Python API) to show in react-table manually. I've read the documentation and I'm trying to use the example here: https://react-table.js.org/#/story/server-side-data
I'm only seeing data in one column and only for 6 records which is really weird. It's probably the way I'm mixing in async/await syntax with the example code which uses a promise. I was able to create a simple react-table fetching data with the same async/await syntax, but when I added the server-side data code from the example (the requestData function) it wouldn't work.
I've spent days on this and looking all over Stackoverflow and the internet. I'm a newbie so please go easy on me. Here's what I have:
import React from 'react'
import { render } from 'react-dom'
import ReactTable from 'react-table'
import api from 'src/api'
import { orderBy } from 'lodash'
// importing react-table css would not work so I added it using cdn link
const requestData = async (pageSize, page, sorted, filtered) => {
// api is a wrapper for axios.create()
const rawData = await api.admin.exercise.feed()
return new Promise((resolve, reject) => {
let filteredData = rawData;
if (filtered.length) {
filteredData = filtered.reduce((filteredSoFar, nextFilter) => {
return filteredSoFar.filter(row => {
return (row[nextFilter.id] + "").includes(nextFilter.value);
});
}, filteredData);
}
const sortedData = orderBy(
filteredData,
sorted.map(sort => {
return row => {
if (row[sort.id] === null || row[sort.id] === undefined) {
return -Infinity;
}
return typeof row[sort.id] === "string"
? row[sort.id].toLowerCase()
: row[sort.id];
};
}),
sorted.map(d => (d.desc ? "desc" : "asc"))
);
const res = {
rows: sortedData.slice(pageSize * page, pageSize * page + pageSize),
pages: Math.ceil(filteredData.length / pageSize)
};
resolve(res);
});
};
export class ExerciseList extends React.Component {
constructor() {
super();
this.state = {
data: [],
pages: null,
loading: true
};
this.fetchData = this.fetchData.bind(this);
}
setLoading(loading) {
this.setState({ loading })
}
fetchData(state, instance) {
this.setLoading(true);
requestData(
state.pageSize,
state.page,
state.sorted,
state.filtered
).then(res => {
this.setState({
data: res.rows,
pages: res.pages,
loading: false
});
});
}
render() {
const { data, pages, loading } = this.state;
return (
<div>
<ReactTable
columns={[
{
Header: "Name",
accessor: "name"
},
{
Header: "Movement",
accessor: "movement"
},
{
Header: "Equipment",
accessor: "equipments"
},
{
Header: "Channel",
accessor: "channel"
},
{
Header: "Level",
accessor: "skill_level"
},
{
Header: "Duration",
accessor: "duration",
filterable: false
},
{
Header: "Injuries",
accessor: "injuries"
},
{
Header: "Is Substitute",
accessor: "has_video",
Cell: ({ value }) => (value? 'Yes': 'No'),
filterable: false
}
]}
data={data}
pages={pages}
loading={loading}
onFetchData={this.fetchData}
manual
filterable
defaultPageSize={10}
className="-striped -highlight"
/>
</div>
);
}
}
render(<ExerciseList />, document.getElementById('datatable'));
Please refer the link for server-side sorting, pagination and manual filtering within the grid
// Component related to methods for sorting, pagination server side and filtering manual filtering with in the grid
import React from 'react'
import 'react-table/react-table.css'
import ReactTable from 'react-table'
import autoBind from 'react-autobind'
import {filterCaseInsensitive} from '../../helper/commonMethods'
class ServerSideAtomGrid extends React.Component {
super(props)
const userDetails = getUserDetails()
this.state = {
page: 0,
pageSizeOptions: [500, 1000, 2000, 4000],
pageSize: 500,
totalRecords: 0,
nextCursor: '*',
cursorList: [{
page: 0,
cursor: '*'
}],
sortFields: {
field: 'created_dtm',
sort: 'desc'
},
columnData,
}
autoBind(this)
}
handlePageChange (page) {
const pageNumber = (page)
const cursorList = this.state.cursorList
let cusrsorMark = ''
_.each(cursorList, (list) => {
if (list.page === pageNumber) {
cusrsorMark = list.cursor
}
})
this.setState({
nextCursor: cusrsorMark,
page: pageNumber
}, () => this.searchData(cusrsorMark, pageNumber))
}
handleSizePerPageChange (pageSize) {
this.resetData(pageSize)
this.searchData('*', 0)
}
handleSorting = (state, instance) => {
const sorted = state
let field = 'created_dtm'
let sort = 'desc'
sorted && sorted.length > 0 && sorted.map(fld => {
field = fld.id
sort = fld.desc ? 'desc' : 'asc'
})
this.setState({
sortFields: {
field,
sort
}
}, () => this.searchData('*', 0))
}
////
searchData('*', 0) {
//Axios call you cna have
}
filterCaseInsensitive (filter, row) {
const id = filter.pivotId || filter.id
return row[id] ? row[id].toString().toLowerCase().includes(filter.value.toLowerCase()) : true
}
render () {
const {
classes, gridData, gridColumns, defaultFilter, totalRecords,
gridPageSizeOptions, gridPage, gridPages, gridPageSize, gridLoading
} = this.props
return (
<div>
<ReactTable
columns={gridColumns}
data={gridData}
onSortedChange={(state, instance) => {
this.handleSorting(state, instance)
}}
filterable={defaultFilter}
defaultFilterMethod={filterCaseInsensitive}
noDataText="Ops No result found!"
defaultPageSize={this.state.pageSize}
className="-highlight"
style={{height: `${totalRecords < 25 ? '' : `800px`}`, width: '100%', textAlign: 'center'}}
pageText={`Total Count : ${totalRecords.toLocaleString()} Page: `}
loading={gridLoading}
page={this.state.page}
pages={this.state.pages}
showPaginationTop
pageSize={this.state.pageSize}
pageSizeOptions={gthis.state.pageSizeOptions}
minRows={25}
manual
onPageChange={page => {
this.setState({page})
this.handlePageChange(page)
}}
onPageSizeChange={(pageSize, page) => {
this.setState({
page,
pageSize
})
this.props.handleSizePerPageChange(pageSize)
}}
showPageJump={false}
/>
</div>
)
}
}
export default (ServerSideAtomGrid)
My Fiddle: https://jsfiddle.net/gowthamguruju/o9ybxqaj/8/

my extjs grid is not showing json data in grid from local host

I am using django framework and getting some data from local host in json format like this:
[{"stu_name": "Aatir"}, {"stu_name": "Mohsin"}, {"stu_name": "Anil"}, {"stu_name": "Anwar"}, {"stu_name": "Amir"}]
now i want to use this data and want to show in extjs grid
my extjs files are as below:
hmak.html
<html>
<head>
<title>Account Manager</title>
<link rel="stylesheet" type="text/css" href="{{MEDIA_URL}}extjs/resources/css/ext-all.css">
<script type="text/javascript" src="{{MEDIA_URL}}extjs/ext-all-debug.js"></script>
<script type="text/javascript" src="{{MEDIA_URL}}extjs/ext-debug.js"></script>
<script type="text/javascript" src="{{MEDIA_URL}}app.js"></script>
</head>
<body>
</body>
</html>
app.js
Ext.Loader.setConfig({ enabled: true });
Ext.application({
requires : [ 'Ext.container.Viewport'],
controllers: ['Users'],
name: 'AM',
appFolder: 'media/app',
launch: function() {
Ext.create('Ext.container.Viewport', {
layout: 'fit',
items: [
{
xtype: 'userlist'
}
]
});
}
});
Users.js(controller)
Ext.define('AM.controller.Users', {
extend: 'Ext.app.Controller',
stores: ['Users'],
models: ['User'],
views: ['user.List', 'user.Edit'],
init: function() {
this.control({
'viewport > userlist': {
itemdblclick: this.editUser
},
'useredit button[action=save]': {
click: this.updateUser
}
});
},
updateUser: function(button) {
var win = button.up('window'),
form = win.down('form'),
record = form.getRecord(),
values = form.getValues();
record.set(values);
win.close();
this.getUsersStore().sync();
},
editUser: function(grid, record) {
var view = Ext.widget('useredit');
view.down('form').loadRecord(record);
}
});
List.js(view)
Ext.define('AM.view.user.List' ,{
extend: 'Ext.grid.Panel',
alias : 'widget.userlist',
store: 'Users',
title : 'All Users',
initComponent: function() {
this.store = {
fields: ["stu_name"]
};
this.columns = [
{header: "stu_name", dataIndex: "stu_name", flex: 1}
];
this.callParent(arguments);
}
});
Edit.js(view)
Ext.define('AM.view.user.Edit', {
extend: 'Ext.window.Window',
alias : 'widget.useredit',
title : 'Edit User',
layout: 'fit',
autoShow: true,
initComponent: function() {
this.items = [
{
xtype: 'form',
items: [
{
xtype: 'textfield',
name : "stu_name",
fieldLabel: "stu_name"
}
]
}
];
this.buttons = [
{
text: 'Save',
action: 'save'
},
{
text: 'Cancel',
scope: this,
handler: this.close
}
];
this.callParent(arguments);
}
});
Users.js(store)
Ext.define('AM.store.Users', {
extend: 'Ext.data.Store',
model: 'AM.model.User',
autoLoad: true,
proxy: {
type: 'ajax',
api: {
read: 'http://127.0.0.1:8000/task/'
},
reader: {
type: 'json',
root: 'users',
successProperty: 'success'
}
}
});
User.js(model)
Ext.define('AM.model.User', {
extend: 'Ext.data.Model',
fields: ["stu_name"]
});
viewport.js
Ext.define('SI.view.Viewport', {
extend: 'Ext.container.Viewport'
});
and in my python I wrote:
def homePage(request):
StuInfo.objects.all().values_list()
return render_to_response('hmak.html', context_instance=RequestContext(request))
which in turn goes to hmak.html and from localhost/task (which I've define in the proxy) the data which it gets is in the json form as I've show you above json data
Now what is my problem that why my grid is not showing?
it just shows the header...
Can anyone please help me with this problem?
I think You have to change the
Ext.define('SI.view.Viewport', {
extend: 'Ext.container.Viewport'
});
to
Ext.define('AM.view.Viewport', {
extend: 'Ext.container.Viewport'
});
and also deleting the store calling inside of the initComponent function.
This might be the source of your problem:
this.store = {
fields: ["stu_name"]
};
In the initComponent function, you are overwriting the store that you defined in the gridpanel class definition. Have you tried deleting that?

Categories