i have this bar graph made with echar, and i want to add information to the tooltip that it shows when you select a bar in the graph, how can i to do that?
this is the graphic code:
option: {
title: {
text: "Unidades que Necesitan Mantenimiento por Kilometro",
//subtext: "Living Expenses in Shenzhen",
},
tooltip: {
trigger: "axis",
axisPointer: {
type: "shadow",
},
},
grid: {
left: "3%",
right: "4%",
bottom: "3%",
containLabel: true,
},
xAxis: [
{
type: "category",
data: [],
axisTick: {
alignWithLabel: true,
},
},
],
yAxis: [
{
type: "value",
},
{
type: "value",
},
],
series: [
{
name: "Kilometraje Excedido",
type: "bar",
barWidth: "60%",
data: [],
},
],
},
here i load actually the information from my request, i want to load the information from Año_del_Modelo and Fecha_del_Ultimo_Servis also i want to add a label that says "Modelo", and "Ultimo Servis":
async obtenerUnidadesMantenimientoImportante() {
var respuesta;
this.url =
this.urlBase + "reporte/obtenerunidadesmantenimientoimportante";
const config = {
headers: {
Authorization: `Bearer ${sessionStorage.getItem("Token")}`,
},
};
respuesta = await this.$http
.get(this.url, config)
.then((response) => response.data);
var i = 0;
while (i < 9) {
this.modelos.push(respuesta[i].Año_del_Modelo);
this.ultMantenimientos.push(respuesta[i].Fecha_del_Ultimo_Servis);
this.option.xAxis[0].data.push(respuesta[i].Unidad);
this.option.series[0].data.push(
respuesta[i].Km_Restante_de_Proximo_Servis * -1
);
i++;
}
},
Related
I am using northwind oData model and using the "SummaryByYear" model to create a line chart. The data looks as follows (for easier representation, only 4 entries are shown):
{
"results": [
{
"__metadata": {
"uri": "https://services.odata.org/V2/Northwind/Northwind.svc/Summary_of_Sales_by_Years(10248)",
"type": "NorthwindModel.Summary_of_Sales_by_Year"
},
"ShippedDate": "1996-07-16T00:00:00.000Z",
"OrderID": 10248,
"Subtotal": "440.00"
},
{
"__metadata": {
"uri": "https://services.odata.org/V2/Northwind/Northwind.svc/Summary_of_Sales_by_Years(10249)",
"type": "NorthwindModel.Summary_of_Sales_by_Year"
},
"ShippedDate": "1996-07-10T00:00:00.000Z",
"OrderID": 10249,
"Subtotal": "1863.40"
},
{
"__metadata": {
"uri": "https://services.odata.org/V2/Northwind/Northwind.svc/Summary_of_Sales_by_Years(10250)",
"type": "NorthwindModel.Summary_of_Sales_by_Year"
},
"ShippedDate": "1996-07-12T00:00:00.000Z",
"OrderID": 10250,
"Subtotal": "1552.60"
},
{
"__metadata": {
"uri": "https://services.odata.org/V2/Northwind/Northwind.svc/Summary_of_Sales_by_Years(10251)",
"type": "NorthwindModel.Summary_of_Sales_by_Year"
},
"ShippedDate": "1996-07-15T00:00:00.000Z",
"OrderID": 10251,
"Subtotal": "654.06"
}
]
}
following is the XML view for Chart:
<chart:ChartContainer id="chartContainer" showFullScreen="true" showZoom="false" title="Sales Summary (by Year)">
<chart:ChartContainerContent>
<chart:content>
<viz:VizFrame id="lineChart" width="auto" uiConfig="{applicationSet:'fiori'}">
</viz:VizFrame>
</chart:content>
</chart:ChartContainerContent>
</chart:ChartContainer>
and this is the controlles onInit function:
onInit: function () {
var northwind = this.getOwnerComponent().getModel("northwind");
var that = this;
northwind.read("/Summary_of_Sales_by_Years", {
method: "GET",
success: function (resp) {
resp["results"].forEach(item => {
item.Subtotal = item.Subtotal.toString().slice(0, -2)
});
var summaryByYear = new JSONModel({
"results": resp["results"]
})
var lineChart = that.getView().byId("lineChart");
lineChart.setVizType('line');
lineChart.setUiConfig({
applicationSet: 'fiori',
});
var oDataset = new FlattenedDataset({
dimensions: [{
axis: 1,
name: 'Year',
value: '{ShippedDate}',
datatype: "date"
}, ],
measures: [{
name: 'Subtotal',
value: '{Subtotal}',
}],
data: {
path: '/results',
},
});
lineChart.setDataset(oDataset);
lineChart.setModel(summaryByYear);
var feedValueAxis = new FeedItem({
uid: 'valueAxis',
type: 'Measure',
values: ['Subtotal'],
}),
feedCategoryAxis = new FeedItem({
uid: 'categoryAxis',
type: 'Dimension',
values: ['Year'],
});
lineChart.addFeed(feedValueAxis);
lineChart.addFeed(feedCategoryAxis);
lineChart.setVizProperties({
general: {
layout: {
padding: 0.04,
},
},
plotArea: {
window: {
start: 'firstDataPoint',
end: 'lastDataPoint'
}
},
valueAxis: {
label: {
formatString: 'axisFormat',
},
title: {
visible: false,
},
},
categoryAxis: {
title: {
visible: false,
},
},
plotArea: {
dataLabel: {
visible: true,
formatString: 'datalabelFormat',
style: {
color: null,
},
},
},
legend: {
title: {
visible: false,
},
},
title: {
visible: false,
text: 'Summary of Sales (by year)',
},
levels: ['month', 'day', 'year'],
interval: {
unit: ''
}
});
}
});
}
following is the result:
I am getting the date in raw timestamp format instead of year and month and also there are weird texts such as "5atalabelfor9at". What am I doing wrong here and please point me to the correct docs if I am missing some kind of config, thanks.
Good Day Developers!
I'm facing issue in JSON object received from MVC controller to AJAX success request.
The response which received is below.
[
{"name":"ERP Developer","value":2},
{"name":"Software Engineer","value":2},
{"name":"Dot Net Developer","value":2},
{"name":"Apex Developer","value":0},
{"name":"test","value":1}
]
But i want to make it like below.
{
"name": [
"ERP Developer",
"Software Engineer"
],
"Value": [
5,
10
]
}
Problem: Because i'm creating Bar chart using ECHARTS library but i want series name instead of number please see below image for reference.
function loadBarChart(data,title = "JobData",subtext = "Artistic Milliners") {
//var BarDBData = data;
var BarDBData = data;
//var BarDBData = JSON.parse('{"name":["ERP Developer","TEST"],"test":[5,10]}');
console.log(BarDBData);
var chartDom = document.getElementById('BarChart');
var myChart = echarts.init(chartDom);
var option;
option = {
title: {
text: title,
subtext: subtext
},
tooltip: {
trigger: 'axis'
},
toolbox: {
show: true,
feature: {
dataView: { show: true, readOnly: false },
magicType: { show: true, type: ['line', 'bar'] },
saveAsImage: { show: true }
}
},
calculable: true,
xAxis: [
{
type: 'category',
// prettier-ignore
//data: ["ERP Developer", "Software Engineer"],
data: BarDBData,
axisLabel: { interval: 0, rotate: 30 }
}
],
yAxis: [
{
type: 'value'
}
],
dataZoom: [
{
show: true,
start: 04,
end: 100
},
{
type: 'inside',
start: 44,
end: 100
},
{
show: true,
yAxisIndex: 0,
filterMode: 'empty',
width: 30,
height: '80%',
showDataShadow: false,
left: '93%'
}
],
series: [
{
name: "test",
type: 'bar',
data: BarDBData,
//data: [2.0, 4.9, 4, 9, 4],
itemStyle: {
color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
{ offset: 0, color: '#83bff6' },
{ offset: 0.5, color: '#188df0' },
{ offset: 1, color: '#188df0' }
])
},
markPoint: {
data: [
{ type: 'max', name: 'Max' },
{ type: 'min', name: 'Min' }
]
}
}
]
};
option && myChart.setOption(option);
}
you can just map through array and extract values into another array
const result = {}
const arr = [{"name":"ERP Developer","value":2},{"name":"Software Engineer","value":2},{"name":"Dot Net Developer","value":2},{"name":"Apex Developer","value":0},{"name":"test","value":1}]
arr.forEach(row => {
for (let i in row) {
if (result[i]) {
result[i].push(row[i])
} else {
result[i] = [row[i]]
}
}
})
console.log(result)
Just reduce() it into the desired shape:
const response = [
{"name":"ERP Developer","value":2},
{"name":"Software Engineer","value":2},
{"name":"Dot Net Developer","value":2},
{"name":"Apex Developer","value":0},
{"name":"test","value":1}
];
const mapped = response.reduce(
(acc,x) => {
acc.name.push( x.name );
acc.Value.push( x.value );
return acc;
},
{ name: [], Value: [] }
);
How can I bind pie chart and line chart together rather than appear one by one? And the pie charts which appear later than line chart will block the line chart. Is there any chance the pie and line can appear together in the end?
The current situation is that
at the beginning,and then.
This is the JS code.
var dom2 = document.getElementById('demo');
var chart = echarts.init(dom2);
var option = {
title: {
text: '中药与疾病'
},
tooltip: {},
legend: {
data: ['中药', '疾病']
},
xAxis: {
data: []
},
yAxis: [
{},
{}
],
series: [
{
name: '中药',
type: 'line',
data: [],
yAxisIndex: 0
},
{
name: '疾病',
type: 'line',
data: [],
yAxisIndex: 1
}
]
}
chart.setOption(option);
$.get('https://gist.githubusercontent.com/Linya-gzl/4d4f388e1b0e3d8e05c38f875b94a97c/raw/8c121acbfaf4aac9eccaf6b81cd1b3614203c185/demo1.json').done(function (data) {
dataArr = JSON.parse(data);
console.log(dataArr);
chart.setOption({
xAxis: {
data: dataArr.map(row => row['categories'])
},
series: [{
name: '中药',
data: dataArr.map(row => row['value1'])
},
{
name: '疾病',
data: dataArr.map(row => row['value2'])
}]
});
function buildPieSeries() {
var len = dataArr.length;
for (var i = 0; i < len; i++) {
option.series.push({
type: 'pie',
radius: 15,
center: [110 + 90 * i, dataArr[i].value2 - 100],
label: {
show: true,
textStyle: {
fontSize: 8
}
},
data: [
{ value: dataArr[i].value1, name: '黄连' },
{ value: dataArr[i].value2, name: '黄芩' },
]
})
}
chart.setOption(option, true);
}
setTimeout(buildPieSeries, 1000);
});
and
<script src="https://cdnjs.cloudflare.com/ajax/libs/echarts/4.7.0/echarts.min.js" integrity="sha256-eKrx6Ly6b0Rscx/PSm52rJsvK76RJyv18Toswq+OLSs=" crossorigin="anonymous"></script>
<script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js'></script>
<div id="demo" style="width: 600px;height:400px;"></div>
I changed your code a bit in the series insertion part, by my opinion need inserting series completely because partial inserts sometimes cause problems with merging data. Also I fixed coordinate calculation, more correct way take the already calculated coordinates from line if they the same.
document.addEventListener("DOMContentLoaded", e => {
var targetNode = document.querySelector('#chartNode');
var chartInstance = echarts.init(targetNode);
var option = {
title: { text: '中药与疾病' },
tooltip: {},
legend: { data: ['中药', '疾病'] },
xAxis: { data: [] },
yAxis: [
{},
{}
],
series: [
{
name: '中药',
type: 'line',
data: [],
yAxisIndex: 0
},
{
name: '疾病',
type: 'line',
data: [],
yAxisIndex: 1
}
]
}
chartInstance.setOption(option);
$.get('https://gist.githubusercontent.com/Linya-gzl/4d4f388e1b0e3d8e05c38f875b94a97c/raw/8c121acbfaf4aac9eccaf6b81cd1b3614203c185/demo1.json').done(function (data) {
dataArr = JSON.parse(data);
chartInstance.setOption({
xAxis: {
data: dataArr.map(row => row['categories'])
},
series: [{
name: '中药',
data: dataArr.map(row => row['value1'])
},
{
name: '疾病',
data: dataArr.map(row => row['value2'])
}]});
pieSeries = chartInstance.getOption().series;
function buildPieSeries() {
var len = dataArr.length;
for (var i = 0; i < len; i++) {
pieSeries.push({
type: 'pie',
radius: 15,
z: 10,
center: chartInstance.getModel().getSeriesByName('中药')[0].getData().getItemLayout(i),
// center: [110 + 90 * i, dataArr[i].value2 - 100],
label: {
show: true,
textStyle: {
fontSize: 8
}},
data: [
{ value: dataArr[i].value1, name: '黄连' },
{ value: dataArr[i].value2, name: '黄芩' },
]
})
};
chartInstance.setOption({ series: pieSeries });
}
setTimeout(() => buildPieSeries(), 1000);
});
});
<script src="https://cdn.jsdelivr.net/npm/echarts#4.7.0/dist/echarts.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="chartNode" style="width: 600px;height:400px;"></div>
I have developed a horizontal Bar chart using Vue-chart.js, all the data and labels are coming from API. The problem is that the value is also visible along with the label, How can I hide the value appearing beside the label? The image is given below
I have the following code.
import { HorizontalBar } from 'vue-chartjs'
export default {
name: 'diagram',
extends: HorizontalBar,
data: () => ({
chartData: '',
score: {},
value: [],
keys: [],
options: {
scales: {
xAxes: [{
ticks: {
scaleShowLabels:false,
}
}],
yAxes: [{
ticks: {
scaleShowLabels:false,
mirror: true
}
}]
},
responsive: true,
},
responsive: true,
maintainAspectRatio: false
}),
created () {
// Overwriting base render method with actual data.
this.$http({
method: 'get',
url: this.base_url + '/exam/api/score/' + this.$store.state.user.id + '/',
auth: {
username: 'my-username',
password: 'my-password'
},
}).then(res => {
console.log(res);
if (res.status == '200') {
console.log(res.data);
this.score = res.data;
for (let v in this.score) {
this.value.push(this.score[v]);
}
for (let key in this.score) {
this.keys.push(key);
}
}
});
this.fillData()
},
mounted(){
this.renderChart(this.chartData, this.options);
},
methods: {
fillData () {
this.chartData = {
labels: this.keys,
datasets: [
{
fillColor: "#ffecbf",
strokeColor: "#dacdd2",
data: this.value,
}
],
}
}
},
watch: {
data: function () {
this._chart.destroy();
this.renderChart(this.chartData, this.options);
},
},
}
please help me out. Thanks in advance.
Hi i have a Kendo grid which works fine but I was wondering if its possible to add another exact one with a button click so i could have multiple instances of the same grid?
I am getting all the data from a sql database.
My code for the grid is ->
function DisplaySearch() {
var textS = $('#searchBox').val();
Textvalue = textS;
$.ajax({
type: "post",
data: JSON.stringify({
search_string: Textvalue,
}),
url: "Search.aspx/display_search",
dataType: "json",
contentType: 'application/json',
success: function (object) {
response(object);
},
complete: function (object) {
},
error: function (object) {
}
});
function response(object) {
$("#searchGrid").kendoGrid({
dataSource: {
data: object.d,
schema: {
model: {
archive_header_key: { type: "number" },
group_Name: { type: "string" },
Server: { type: "string" },
archive: { type: "string" },
display_name: { type: "string" },
file_written: { type: "number" },
session_ID: { type: "string" },
},
},
pageSize: 20,
},
reorderable: true,
navigatable: true,
selectable: "multiple",
scrollable: true,
sortable: true,
filterable: false,
columnMenu: true,
pageable: {
input: true,
numeric: true
},
columns: [
{ field: "archive_header_key", title: "Key", width: 50 },
{ field: "Server", title: "Server", width: 75 },
{ field: "group_Name", title: "Group", width: 75 },
{ field: "archive", title: "Archive", width: 50 },
{ field: "display_name", title: "Display name", width: 300 },
{ field: "file_written", title: "Files", width: 50 },
{ field: "session_ID", title: "Session", width: 200 },
]
});
}
};
any help would be appreciated.
Of course you can! You only need to make sure that the id of the grid is unique.
This code will add a div to a given container and create a grid - with any button click a new grid. Hope it works, I haven't tested it.
var gridNr = 1;
$("#btn").click(function(e){
$("#gridContainer").append("<div id='grid_'" + gridNr + " />");
$("#grid_" + gridNr).kendoGrid({ ... your grid code here ... });
gridNr++;
})