JavaFX のチャートを使いこなせるようになりたいと、LineChart, BarChart のサンプルを紹介してきました。今回は PieChart を利用した円グラフ(パイチャート)のサンプルを紹介します。
動作環境は次の通りです。
- OS: Fedora 22 x86_64
- jdk1.8.0_45-1.8.0_45-fcs.x86_64 (Oracle)
- IDE: NetBeans IDE 8.0.2
リスト:PieChartSample.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | package piechartsample; import javafx.application.Application; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.geometry.Side; import javafx.scene.Scene; import javafx.scene.chart.PieChart; import javafx.stage.Stage; public class PieChartSample extends Application { @Override public void start(Stage stage) { // http://www.kudamononavi.com/graph/trade/ ObservableList<PieChart.Data> piechartData = FXCollections.observableArrayList( new PieChart.Data( "温州みかん" , 47200 ), new PieChart.Data( "りんご" , 39700 ), new PieChart.Data( "かき" , 22600 ), new PieChart.Data( "くり" , 21700 ), new PieChart.Data( "ぶどう" , 18600 )); final PieChart piechart = new PieChart(piechartData); piechart.setTitle( "果物生産ランキング(作付面積)" ); piechart.setLegendSide(Side.RIGHT); Scene scene = new Scene(piechart, 600 , 400 ); scene.getStylesheets().add(getClass().getResource( "PieChart.css" ).toExternalForm()); stage.setScene(scene); stage.show(); } public static void main(String[] args) { launch(args); } } |
CSS は、今回も折れ線グラフに使ったものをベースにしています。
リスト:PieChart.css
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | .chart { -fx- padding : 10px ; -fx- background-color : white ; } .chart-content { -fx- padding : 10px ; } .chart-title { -fx- font-size : 18pt ; } .chart-pie { -fx- border-color : rgba( 0 , 0 , 0 , 0.2 ); -fx-background-radius: 0 ; -fx-background-insets: 0 ; } .chart-pie-label { -fx- font-size : 12pt ; } .default-color 0 .chart-pie { -fx- background-color : orange; } .default-color 1 .chart-pie { -fx- background-color : lawngreen; } .default-color 2 .chart-pie { -fx- background-color : lightpink; } .default-color 3 .chart-pie { -fx- background-color : khaki; } .default-color 4 .chart-pie { -fx- background-color : skyblue; } .chart-pie-label-line { } .chart-pie-label { } .chart-legend { -fx- font-size : 9pt ; -fx- background-color : transparent ; } |
実行例を以下に示します。
棒グラフの場合と同じ理由で、円グラフでも作成するときには配色に悩みます。さらに、Excel などでは文字の大きさと円グラフの領域を最大にするのに苦労します。その苦労は JavaFX でも同じです。なにか良い方法がないかと思うのですが、時間を掛けて検討するほど円グラフの使用頻度が高くないので、いつも間に合わせの対応で済ませてしまっています。
参考サイト
- JavaFX CSS Reference Guide
- Using JavaFX Charts: Styling Charts with CSS | JavaFX 2 Tutorials and Documentation
- chartとgraphの違い | 違いがわかると英語がわかる
0 件のコメント:
コメントを投稿