你好,我在我的JavaScript核心MVC项目上使用了.NET开源图形库。我不知道如何在条形图的轴上使用JSON数据。在这里,我曾经使用条形图来采样默认数据。
Index.cshtml
<div id="locationDiv"></div>
<script>
var trace1 = {
type: 'bar',
x: ["İstanbul", "Ankara", "İzmir", "Antalya"],
y: [50, 40, 20, 15],
marker: {
color: '#C8A2C8',
line: {
width: 2.5
}
}
};
var locationData = [trace1];
var locationLayout = {
title: 'Locations',
yaxis: {
title: 'number'
},
xaxis: {
title: 'location name'
},
font: { size: 18 }
};
Plotly.newPlot('locationDiv', locationData, locationLayout, { responsive: true });
</script>我试着从我的数据库中得到x轴值。
Index.cshtml
<div id="locationDiv"></div>
@section scripts {
<script>
$.ajax({
type: "POST",
url: "/Line/Dashboards",
dataSrc: "",
success: function (response) {
successFunc(response);
}
});
function successFunc(jsondata) {
var trace1 = {
type: 'bar',
json: jsondata,
x: "locationName", //Default value:= x: ["İstanbul", "Ankara", "İzmir"],
//POSTMAN result:= [{"locationName": "İstanbul"},{"locationName": "Ankara"},{"locationName": "İzmir"}]
y: [50, 40, 20],
marker: {
color: '#3399FF',
line: {
width: 2.5
}
}
};
var locationData = [trace1];
var locationLayout = {
yaxis: {
title: 'number'
},
xaxis: {
title: 'location name'
},
font: { size: 18 }
};
Plotly.newPlot('locationDiv', locationData, locationLayout, { responsive: true });
}
</script>
}LineController.cs
[HttpPost]
public IActionResult Dashboards()
{
var dashboardDataList = _lineService.GetLineList();
var totalRecords = dashboardDataList.Count();
var DashboardDataResult = from line in dashboardDataList
select new
{
LocationName = line.Location.LocationName
};
DashboardDataResult = DashboardDataResult.Distinct();
return Json(DashboardDataResult);
}我的道路是真的。我和邮差试过了,结果是
[{"locationName": "İstanbul"},{"locationName": "Ankara"},{"locationName": "İzmir"}]发布于 2020-01-23 08:13:23
尝试以下方法:
function successFunc(jsondata) {
function unpack(rows, key) {
return rows.map(function(row) { return row[key]; });
}
var x = unpack(jsondata, 'locationName');
var trace1 = {
type: 'bar',
json: jsondata,
x: x,
y: [50, 40, 20,15],
marker: {
color: '#3399FF',
line: {
width: 2.5
}
}
};
var locationData = [trace1];
var locationLayout = {
title:'Locations',
yaxis: {
title: 'number'
},
xaxis: {
title: 'location name'
},
font: { size: 18 }
};
Plotly.newPlot('locationDiv', locationData, locationLayout, { responsive: true });
}参考资料:https://plot.ly/javascript/axes/#set-and-style-axes-title-labels-and-ticks
https://stackoverflow.com/questions/59856298
复制相似问题