java 左右横向柱状图
时间: 2023-08-11 14:24:09 浏览: 190
生成Java左右横向柱状图可以使用Java的图形库,例如JavaFX或JFreeChart。
以下是一个使用JFreeChart库生成左右横向柱状图的示例代码:
```java
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.JFrame;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.renderer.category.BarRenderer;
import org.jfree.data.category.DefaultCategoryDataset;
public class HorizontalBarChartExample extends JFrame {
public HorizontalBarChartExample() {
// Create dataset
DefaultCategoryDataset dataset = new DefaultCategoryDataset();
dataset.addValue(1, "Series 1", "Category 1");
dataset.addValue(2, "Series 1", "Category 2");
dataset.addValue(3, "Series 1", "Category 3");
dataset.addValue(4, "Series 1", "Category 4");
dataset.addValue(5, "Series 1", "Category 5");
// Create chart
JFreeChart chart = ChartFactory.createBarChart(
"Horizontal Bar Chart Example",
"Value",
"Category",
dataset,
PlotOrientation.HORIZONTAL,
false,
true,
false);
// Set chart background color
chart.setBackgroundPaint(Color.white);
// Get plot
CategoryPlot plot = chart.getCategoryPlot();
// Set plot background color
plot.setBackgroundPaint(Color.lightGray);
// Set axis ranges
NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
rangeAxis.setRange(0, 10);
// Set bar colors
BarRenderer renderer = (BarRenderer) plot.getRenderer();
renderer.setSeriesPaint(0, Color.blue);
// Set category label positions
CategoryAxis domainAxis = plot.getDomainAxis();
domainAxis.setCategoryLabelPositions(CategoryLabelPositions.STANDARD);
// Create chart panel
ChartPanel chartPanel = new ChartPanel(chart);
chartPanel.setPreferredSize(new Dimension(500, 300));
// Add chart panel to frame
setContentPane(chartPanel);
}
public static void main(String[] args) {
HorizontalBarChartExample example = new HorizontalBarChartExample();
example.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
example.pack();
example.setLocationRelativeTo(null);
example.setVisible(true);
}
}
```
该代码创建了一个左右横向柱状图,并使用了JFreeChart库中的一些属性来设置图表的外观和行为。你可以根据需要更改这些属性来创建符合你需求的左右横向柱状图。
阅读全文