問題描述
如何使用 XChart 使 Y 軸上的限制相同? (How to make limits on the Y axis be the same using XChart?)
I am trying to plot a series of functions that are similar. The domain is [0,1] and the range always in say [‑3,3].
I want the limits on the Y axis to be the same for each graph. Trying to set the series y min and y max does not seem to work.
Is there a way to make the limits on the Y axis be the same on each graph?
import java.math.BigDecimal;
import java.util.*;
import com.xeiam.xchart.*;
public class Bug {
static void plot(Chart chart,int n) {
chart.setTitle("title");
chart.setXAxisTitle("X");
chart.setYAxisTitle("Y");
List<Number> x=new ArrayList<Number>();
List<Number> y=new ArrayList<Number>();
String seriesName=addOneSeries(chart,n,x,y);
}
private static String addOneSeries(Chart chart,int n,List<Number> x,List<Number> y) {
for(int i=0;i<=10;i++) {
x.add(i/10.);
y.add(i*n/10.);
}
String seriesName="series "+n;
Series series=chart.addSeries(seriesName,x,y);
series.xMin=BigDecimal.ZERO;
series.xMax=BigDecimal.ONE;
series.yMin=new BigDecimal(‑5);
series.yMax=new BigDecimal(5);
return seriesName;
}
public static void main(String[] args) {
for(int i=0;i<4;i++) {
Chart chart=new Chart(700,500);
plot(chart,i);
new SwingWrapper(chart).displayChart();
}
}
}
‑‑‑‑‑
參考解法
方法 1:
Setting the min and max values on a Chart
is now possible with XChart. Below is a rework of OP's Bug class that demonstrates this. At this moment, since it's a brand new feature, you'll have to get an xchart‑2.0.0‑SNAPSHOT jar here in order to see this capability. Please feel free to ask for help or request more features!
public class NoBug {
static void plot(Chart chart, int n) {
chart.setChartTitle("title");
chart.setXAxisTitle("X");
chart.setYAxisTitle("Y");
List<Number> x = new ArrayList<Number>();
List<Number> y = new ArrayList<Number>();
String seriesName = addOneSeries(chart, n, x, y);
}
private static String addOneSeries(Chart chart, int n, List<Number> x, List<Number> y) {
for (int i = 0; i <= 10; i++) {
x.add(i / 10.);
y.add(i * n / 10.);
}
String seriesName = "series " + n;
Series series = chart.addSeries(seriesName, x, y);
chart.getStyleManager().setxAxisMin(0);
chart.getStyleManager().setxAxisMax(1);
chart.getStyleManager().setyAxisMin(‑5);
chart.getStyleManager().setyAxisMax(5);
return seriesName;
}
public static void main(String[] args) {
for (int i = 0; i < 4; i++) {
Chart chart = new LineChart(700, 500);
plot(chart, i);
new SwingWrapper(chart).displayChart();
}
}
}
方法 2:
Update 2020‑10‑15
These methods now use a capitalized X
or Y
:
.setXAxisMin()
.setXAxisMax()
.setYAxisMin()
.setYAxisMax()
See https://knowm.org/javadocs/xchart/org/knowm/xchart/style/AxesChartStyler.html#setXAxisMin(java.lang.Double)
(by Ray Tayek、herrtim、Alan Thompson)