gpt4 book ai didi

java - 使 JFreeChart CategoryPlot 看起来像 Flot.js 条形图

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:25:36 25 4
gpt4 key购买 nike

概览

我一直在尝试模仿 flot.js下图显示在 JFreeCharts 中。

enter image description here

到目前为止,我已经在大多数元素上取得了成功,例如具有透明度的单个条形颜色、x 和 y 网格线以及背景。

enter image description here

我现在需要实现的是:

  • 各个栏的边框颜色
  • 实心黑色图表轮廓
  • 推到图表顶部的最高 y 轴值

到目前为止我取得的成就

单独的条形边框颜色

对于单独的条形边框颜色,我找到了建议使用代码的线程“Adding border color/stroke to individual Bars in Bar Chart?

Color borderColor = buildColorMap.get(build);
renderer.setDrawBarOutline(true);
renderer.setSeriesOutlinePaint(iterator, borderColor);

与我目前使用的适用于所有酒吧的那个不同

// other colors
renderer.setSeriesOutlinePaint(3, new Color(213, 94, 0));
renderer.setSeriesOutlinePaint(4, new Color(204, 121, 167));
renderer.setSeriesOutlineStroke(0, new BasicStroke(2.5f));

图表大纲

对于图表的大轮廓,我看到了 setOutlineStroke但是 API 说

Deprecated. This method should no longer be used (as of version 1.0.6). It is sufficient to rely on setSeriesOutlineStroke(int, Stroke) and setBaseOutlineStroke(Stroke). Sets the outline stroke for ALL series and sends a RendererChangeEvent to all registered listeners.

因此我去了setBaseOutlineStroke什么也没发生(仍然和上面的照片一样)!

renderer.setBaseOutlineStroke(new BasicStroke(2.5f), true);

flot.js-类似 y 轴的处理和定位

对于 flot.js 中的 y 轴编号,我能够使用函数(其中数据放在 double 数组中;只有五个实例,所以我不需要更复杂的数据结构):

private static double getHighestArrayValue(double[] array) {
double max = 0;
for (int i = 1; i < array.length; i++) {
if (array[i] > max) {
max = array[i];
}
}
return max;
}

private static double getRoundedUpMultipleOfTen(double number) {
return ((number + 9) / 10) * 10;
}

其中生成图表的用法是:

CategoryPlot plot = ...

final NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
rangeAxis.setRange(0,
getRoundedUpMultipleOfTen(getHighestArrayValue(dataValues)));
rangeAxis.setTickUnit(new NumberTickUnit(10));

导致

enter image description here

现在的问题是如何将 50 推到图表的顶部,我不知道该怎么做。


这是我为任何感兴趣的人提供的完整代码(“Generate Pie Chart/Bar Graph In PDF Using IText & JFreeChart”中 Viral Patel 的修改代码:

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Paint;
import java.awt.geom.Rectangle2D;
import java.io.FileOutputStream;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.StandardChartTheme;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.axis.NumberTickUnit;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.renderer.category.BarRenderer;
import org.jfree.chart.renderer.category.CategoryItemRenderer;
import org.jfree.chart.renderer.category.StandardBarPainter;
import org.jfree.data.category.DefaultCategoryDataset;

import com.itextpdf.text.Document;
import com.itextpdf.text.Font;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfTemplate;
import com.itextpdf.text.pdf.PdfWriter;

public class ChartDemo {
public static void main(String[] args) {
writeChartToPDF(generateBarChart(), 800, 500, "D://barchart.pdf");
}

public static void writeChartToPDF(JFreeChart chart, int width, int height,
String fileName) {
PdfWriter writer = null;
Document document = new Document(PageSize.A4.rotate(), 0, 0, 0, 0);

try {
writer = PdfWriter.getInstance(document, new FileOutputStream(
fileName));
document.open();
PdfContentByte contentByte = writer.getDirectContent();

PdfTemplate template = contentByte.createTemplate(width, height);
Graphics2D graphics2d = template.createGraphics(width, height);
// controls size of image
Rectangle2D rectangle2d = new Rectangle2D.Double(10, -10, width,
height);

chart.draw(graphics2d, rectangle2d);

graphics2d.dispose();
contentByte.addTemplate(template, 0, 0);

} catch (Exception e) {
e.printStackTrace();
}
document.close();
}

static class CustomRenderer extends BarRenderer {

private Paint[] colors;

int transparency = 95;

// http://www.cookbook-r.com/Graphs/Colors_(ggplot2)/
public CustomRenderer() {
this.colors = new Paint[] { new Color(1, 158, 115, transparency),
new Color(240, 228, 66, transparency),
new Color(0, 114, 178, transparency),
new Color(213, 94, 0, transparency),
new Color(204, 121, 167, transparency) };
}

public Paint getItemPaint(final int row, final int column) {
return this.colors[column % this.colors.length];
}
}

public static JFreeChart generateBarChart() {

double[] dataValues = { 40.66, 37.82, 43.16, 32.62, 41.39 };
Paint[] colors = { new Color(1, 158, 115), new Color(240, 228, 66),
new Color(0, 114, 178), new Color(213, 94, 0),
new Color(204, 121, 167) };

DefaultCategoryDataset dataSet = new DefaultCategoryDataset();
for (int i = 0; i < dataValues.length; i++) {
dataSet.setValue(dataValues[i], "Population", (i + 1) * 2 + "");
}

ChartFactory.setChartTheme(StandardChartTheme.createLegacyTheme());
JFreeChart chart = ChartFactory.createBarChart("", "Team number",
"Solved problems (%)", dataSet, PlotOrientation.VERTICAL,
false, true, false);
chart.setBackgroundPaint(Color.WHITE);

final CategoryPlot plot = chart.getCategoryPlot();
((BarRenderer) plot.getRenderer())
.setBarPainter(new StandardBarPainter());

plot.setBackgroundPaint(Color.WHITE);

plot.setDomainGridlinesVisible(true);
plot.setRangeGridlinesVisible(true);

plot.setDomainGridlineStroke(new BasicStroke(0.25f));
plot.setRangeGridlineStroke(new BasicStroke(0.25f));

plot.setDomainGridlinePaint(new Color(204, 204, 204));
plot.setRangeGridlinePaint(new Color(204, 204, 204));

java.awt.Font fontGraphLabel = new java.awt.Font("Helvetica",
Font.NORMAL, 12);
java.awt.Font fontGraphTicks = new java.awt.Font("Helvetica",
Font.NORMAL, 10);
plot.getDomainAxis().setLabelFont(fontGraphLabel);
plot.getRangeAxis().setLabelFont(fontGraphLabel);
plot.getDomainAxis().setTickLabelFont(fontGraphTicks);
plot.getRangeAxis().setTickLabelFont(fontGraphTicks);

CategoryItemRenderer renderer = new CustomRenderer();
plot.setRenderer(renderer);

final NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
rangeAxis.setRange(0,
getRoundedUpMultipleOfTen(getHighestArrayValue(dataValues)));
rangeAxis.setTickUnit(new NumberTickUnit(10));

final BarRenderer renderer1 = (BarRenderer) plot.getRenderer();
renderer1.setDrawBarOutline(true);
renderer1.setShadowVisible(false);

renderer1.setSeriesOutlinePaint(0, new Color(204, 121, 167));
renderer1.setSeriesOutlinePaint(1, new Color(213, 94, 0));
renderer1.setSeriesOutlineStroke(0, new BasicStroke(2.5f));

renderer1.setBaseOutlineStroke(new BasicStroke(10f), true);

return chart;
}

private static double getHighestArrayValue(double[] array) {
double max = 0;
for (int i = 1; i < array.length; i++) {
if (array[i] > max) {
max = array[i];
}
}
return max;
}

private static double getRoundedUpMultipleOfTen(double number) {
return ((number + 9) / 10) * 10;
}

}

最佳答案

我不是 Java 专家,但我会尝试一下我的做法(所有代码都未经测试)...

假设您有如下所示的 flot 代码:

<div id="placeholder" style="width:300px;height:200px"></div>

$(function() {
var series = {data: [[0, 5.2], [1, 3], [2, 9.2], [3, 10]],
lines: {show: false},
bars: {show: true, barWidth: 0.75, align:'center'}}

somePlot = $.plot("#placeholder", [ series ], {});
});

您需要将此代码作为字符串,然后对其进行 Base64 编码(在变量 base64FlotCode 中)。

创建一个如下所示的 phantomJS 脚本(另存为 phantomJSScript.js):

var system = require('system');    
var html = system.args[1];
var page = require('webpage').create();

page.onLoadFinished = function(status) {
var clipRect = page.evaluate(
function()
{
var el = document.querySelector('#placeholder');
return el.getBoundingClientRect();
}
);

page.clipRect = {
top: clipRect.top,
left: clipRect.left,
width: clipRect.width,
height: clipRect.height
};
page.render('/path/to/myPlot.png');

phantom.exit();
};

function b64_to_utf8(str) {
return decodeURIComponent(escape(window.atob(str)));
}

page.content = b64_to_utf8(html);

现在您可以将此脚本称为:

List<String> args = new ArrayList<String>();
args.add ("/path/to/phamtomjs.exe");
args.add ("/path/to/phantomJSScript.js");
args.add (base64FlotCode);
ProcessBuilder pb = new ProcessBuilder (args);
Process p = pb.start();
p.waitFor();

编辑

除了向 phantomJS 传递您的 flot 代码字符串,您还可以将其指向您的网页:

var system = require('system');      
var page = require('webpage').create();

page.open('http://www.mywebpage.com', function() {
var clipRect = page.evaluate(
function()
{
var el = document.querySelector('#placeholder');
return el.getBoundingClientRect();
}
);

page.clipRect = {
top: clipRect.top,
left: clipRect.left,
width: clipRect.width,
height: clipRect.height
};
page.render('/path/to/myPlot.png');

phantom.exit();
};

关于java - 使 JFreeChart CategoryPlot 看起来像 Flot.js 条形图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21936750/

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