是否可以更改条形颜色?
我编写了一个简单的计数程序。
我想再实施一件事:如果计数大于200,请使用蓝色绘制条形图。如果没有,请使用黄色。
目前,所有条形颜色均为红色。
所以,我想问一下,是否可以更改条形颜色?
如果是,有人可以给我一些指导来实现吗?
提前致谢!
附件是我的编码:
<%@page contentType="text/html"%>
<%@page import="java.io.*" %>
<%@page import="java.sql.*" %>
<%@page import="org.jfree.data.category.*" %>
<%@page import="org.jfree.chart.*" %>
<%@page import="org.jfree.chart.plot.*" %>
<html>
<body>
<%
DefaultCategoryDataset dataset = new DefaultCategoryDataset();
try
{
Class.forName("com.mysql.jdbc.Driver");
java.sql.Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/delivery","root","root");
Statement sta = con.createStatement();
ResultSet res = sta.executeQuery("SELECT inventory, subject from statistics");
int count;
String subject;
while (res.next())
{
count = res.getInt("inventory");
subject = res.getString("subject");
dataset.addValue(count,"enrollment count statistics", subject);
}
}
catch (Exception e) {
System.err.println(e.getMessage());
}
JFreeChart bar = ChartFactory.createBarChart("Enrollment Chart", "subject","Count",dataset, PlotOrientation.HORIZONTAL,true, false, false);
//BarRenderer renderer = (BarRenderer) bar.getCategoryPlot().getRenderer();
String fileName = "/bar.png";
String file = application.getRealPath("/") + fileName;
try
{
FileOutputStream fileOut = new FileOutputStream(file);
ChartUtilities.writeChartAsPNG(fileOut, bar, 300, 300);
}
catch (IOException e)
{
out.print(e);
}
%>
<img src="/delivery/bar.png" alt="subject Bar Chart" />
</body>
</html>
答案 0 :(得分:5)
魔法是getItemPaint(int,int) method的BarRenderer class。
一个例子是http://javabeanz.wordpress.com/2007/07/04/creating-barcharts-with-custom-colours-using-jfreechart/
你要做的是:
class CustomRenderer extends BarRenderer
{
public CustomRenderer()
{
}
public Paint getItemPaint(final int row, final int column)
{
// returns color depending on y coordinate.
return (row > 200) ? Color.blue : Color.yellow ;
}
}
然后在调用ChartFactory.createBarChart之后,执行
final CategoryPlot plot = chart.getCategoryPlot();
CategoryItemRenderer renderer = new CustomRenderer();
plot.setRenderer(renderer);
答案 1 :(得分:4)
Plot plot = bar.getPlot();
BarRenderer barRenderer = (BarRenderer)plot.getRenderer();
barRenderer.setSeriesPaint(0, Color.gray);
获取BarRenderer的句柄并在其上调用setSeriesPaint(int series,java.awt.Paint paint)。
答案 2 :(得分:2)
看一下这个链接
<强> JFreeChart: Bar Chart Demo 3: different colors within a series 强>
/**
* A custom renderer that returns a different color for each item in a single series.
*/
class CustomRenderer extends BarRenderer {
/** The colors. */
private Paint[] colors;
/**
* Creates a new renderer.
*
* @param colors the colors.
*/
public CustomRenderer(final Paint[] colors) {
this.colors = colors;
}
/**
* Returns the paint for an item. Overrides the default behaviour inherited from
* AbstractSeriesRenderer.
*
* @param row the series.
* @param column the category.
*
* @return The item color.
*/
public Paint getItemPaint(final int row, final int column) {
return this.colors[column % this.colors.length];
}
}