gpt4 book ai didi

javascript - 带有 Flot 的样式特定条形柱

转载 作者:行者123 更新时间:2023-11-28 12:13:26 25 4
gpt4 key购买 nike

我正在使用 Flot 创建条形图。但是,我需要为某些列添加特殊样式。这可能吗?

我的 HTML 看起来像这样:

<div id="monthly-usage" style="width: 100%; height: 400px;"></div>

我的 JS 是这样的:

somePlot = null;

$(function() {
//Data from this year and last year
var thisYear = [
[3, 231.01],
[4, 219.65],
[5, 222.47],
[6, 223.09],
[7, 248.43],
[8, 246.22]
];

var lastYear = [
[3, 171.7],
[4, 130.62],
[5, 163.03],
[6, 166.46],
[7, 176.16],
[8, 169.04]
];

var usageData = [{
//Usage this year
label: "2014",
data: thisYear,
bars: {
show: true,
barWidth: .3,
fill: true,
lineWidth: 0,
order: 1,
fillColor: 'rgba(194, 46, 52, .85)'
},
color: '#c22e34'
}, {
//Usage last year to compare with current usage
label: "2013",
data: lastYear,
bars: {
show: true,
barWidth: .3,
fill: true,
lineWidth: 0,
order: 2,
fillColor: 'rgba(73, 80, 94, .85)'
},
color: '#49505e'
}];

//X-axis labels
var months = [
[0, "Jan"],
[1, "Feb"],
[2, "Mar"],
[3, "Apr"],
[4, "Maj"],
[5, "Jun"],
[6, "Jul"],
[7, "Aug"],
[8, "Sep"],
[9, "Okt"],
[10, "Nov"],
[11, "Dec"]
];

//Draw the graph
somePlot = $.plot(('#monthly-usage'), usageData, {
grid: {
color: '#646464',
borderColor: 'transparent',
hoverable: true
},
xaxis: {
ticks: months,
color: '#d4d4d4'
},
yaxis: {
tickSize: 50,
tickFormatter: function(y, axis) {
return y + " kWh";
}
},
legend: {
show: false
}
});

var ctx = somePlot.getCanvas().getContext("2d"); // get the context from plot
var data = somePlot.getData()[0].data; // get your series data
var xaxis = somePlot.getXAxes()[0]; // xAxis
var yaxis = somePlot.getYAxes()[0]; // yAxis
var offset = somePlot.getPlotOffset(); // plots offset
var imageObj = new Image(); // create image
imageObj.onload = function() { // when finish loading image add to canvas
xPos = xaxis.p2c(data[4][0]) + offset.left;
yPos = yaxis.p2c(data[4][1]) + offset.top;
ctx.drawImage(this, xPos, yPos);
xPos = xaxis.p2c(data[5][0]) + offset.left;
yPos = yaxis.p2c(data[5][1]) + offset.top;
ctx.drawImage(this, xPos, yPos);
};
imageObj.src = 'path/to/file.png'; // set it's source to kick off load
});
});

最理想的是,我想在第 5 条和第 6 条中插入一个图标来警告用户。或者,我想更改第 5 条和第 6 条的颜色。关于如何解决这个问题有什么想法吗?

编辑:我已经根据 Mark 的有效答案更新了我的 JS。

@Mark,我怎样才能正确定位图像。他们有点不对劲。我需要红色条内的图像而不是条形图之外的图像。我正在尝试对此进行微调,但似乎我无法使用例如“0.5”。我使用与您的版本不同的并排栏。

xPos = xaxis.p2c(data[4][0]) + offset.left;
yPos = yaxis.p2c(data[4][1]) + offset.top;

This is how the images are placed right now

最佳答案

您不能完全按照标准选项执行您的要求,但有几种可能的方法:

  1. 编写您自己的绘图方法并使用 Hook 安装它以代替标准的 flot 绘图代码。这显然需要大量工作,但您将完全控制如何呈现数据。 (也就是说,我不推荐它。)

  2. 将您的数据分成两个不同的数据集。一个数据集的第 5 条和第 6 条会有虚拟值(例如 0,或者你的最小值)。第二个数据集对所有的条都有虚拟值, 5 和 6 除外。然后你可以设置样式“两个”数据集独立,给每一个,例如不同的颜色。将这两个集合绘制成堆叠条形图,并根据您的图表进行适当的其他样式调整。

(仅供引用,jsDataV.is 中有相当多的信息和示例。请查看“书籍”部分;第 2 章专门介绍 flot。)

关于javascript - 带有 Flot 的样式特定条形柱,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26590302/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com