I have the following chart which is displaying some values.
I would like to hide/ remove values on the right side, because on the left side are enough.
See image below:
And code is following:
public class MainActivity extends AppCompatActivity implements
OnChartValueSelectedListener{
private LineChart mDataLineChart;
private RelativeLayout mRelativeLayout;
private LineChart mChart;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_linechart);
// Set chart
setChart();
// add data
setData2(3, 155);
// ANIMATE CHART
animateChart();
}
private void setChart() {
mChart = (LineChart) findViewById(R.id.chart1);
mChart.setOnChartValueSelectedListener(this);
////////////////////////////////
// SET DESCRIPTION COLOR
////////////////////////////////
mChart.setDescriptionColor(getResources().getColor(R.color.chart_desc_color));
////////////////////////////////
// BORDERS SURROUNDING THE CHART
////////////////////////////////
mChart.setDrawBorders(true);
mChart.setBorderColor(getResources().getColor(R.color.chart_border));
mChart.setBorderWidth(2);
////////////////////////////////
// CHART BG COLOR
////////////////////////////////
mChart.setBackgroundColor(getResources().getColor(R.color.chart_bg));
////////////////////////////////
// GRID BG COLOR
////////////////////////////////
mChart.setDrawGridBackground(true);
mChart.setGridBackgroundColor(getResources().getColor(R.color.chart_bg));
////////////////////////////////
// OTHER SETTINGS
////////////////////////////////
mChart.setDescription("");
mChart.setNoDataTextDescription("You need to provide data for the chart.");
// enable touch gestures
mChart.setTouchEnabled(true);
mChart.setDragDecelerationFrictionCoef(0.9f);
// enable scaling and dragging
mChart.setDragEnabled(true);
mChart.setScaleEnabled(true);
mChart.setHighlightPerDragEnabled(true);
// if disabled, scaling can be done on x- and y-axis separately
mChart.setPinchZoom(true);
}
private void setData2(int count, float range) {
////////////////////////////////
// X axis values (labels)
////////////////////////////////
ArrayList<String> xVals = new ArrayList<String>();
for (int i = 0; i < count; i++) {
xVals.add((i) + " day");
}
////////////////////////////////
// Y axis values (value in linechart)
////////////////////////////////
ArrayList<Entry> yVals1 = new ArrayList<Entry>();
for (int i = 0; i < count; i++) {
float mult = range / 2f;
float val = (float) (Math.random() * mult) + 50;// + (float)
// ((mult *
// 0.1) / 10);
yVals1.add(new Entry(val, i));
}
////////////////////////////////
// SETTING FOR LINEAR LINE
////////////////////////////////
LineDataSet set1 = new LineDataSet(yVals1, "Pressure mm/Hg");
set1.setAxisDependency(AxisDependency.LEFT);
set1.setLineWidth(2f);
set1.setCircleSize(5f);
set1.setColor(getResources().getColor(R.color.chart_line_color));
set1.setCircleColor(getResources().getColor(R.color.chart_line_color));
set1.setFillColor(getResources().getColor(R.color.chart_line_color));
set1.setDrawCircleHole(true);
ArrayList<LineDataSet> dataSets = new ArrayList<LineDataSet>();
dataSets.add(set1); // add the datasets
////////////////////////////////
// SETTING FOR DATASET (FONT SIZE, )
////////////////////////////////
LineData data = new LineData(xVals, dataSets);
data.setValueTextColor(Color.BLACK);
data.setValueTextSize(9f);
////////////////////////////////
// SET WHOLE DATASET TO CHART
////////////////////////////////
mChart.setData(data);
}
private void animateChart() {
////////////////////////////////
// ANIMATION DURATION
////////////////////////////////
mChart.animateX(1000);
////////////////////////////////
// SET LEGEND BOTTOM DATA TEXT
////////////////////////////////
XAxis xAxis = mChart.getXAxis();
xAxis.setTextSize(12f);
xAxis.setTextColor(Color.BLACK);
xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
xAxis.setSpaceBetweenLabels(1);
}
#Override
public void onValueSelected(Entry e, int dataSetIndex, Highlight h) {
Log.i("Entry selected", e.toString());
}
#Override
public void onNothingSelected() {
Log.i("Nothing selected", "Nothing selected.");
}
}
I tried to search in documentation on Github:
https://github.com/PhilJay/MPAndroidChart/wiki/The-Axis
But without luck.
How can i remove values from right please?
Many thanks for any advice.
YAxis yAxisRight = mChart.getAxisRight();
yAxisRight.setEnabled(false);
put this code on your setChart();
You may want to check example application and corresponding codes. The application includes 2 related examples: Line Chart and Line Chart (Dual YAxis). The first is what you want and the latter is what you have right know.
App link: https://play.google.com/store/apps/details?id=com.xxmassdeveloper.mpchartexample
Code: https://github.com/PhilJay/MPAndroidChart/tree/master/MPChartExample
Related
I m using MPAndroidChart Combined Chart to display a Bar & Scatter chart. On click on points of Scatter Graph i m showing a custom marker which is as below :
public class YourMarkerView extends MarkerView {
private TextView tvContent;
private RelativeLayout mainbackground;
/**
* Constructor. Sets up the MarkerView with a custom layout resource.
*
* #param context
* #param layoutResource the layout resource to use for the MarkerView
*/
public YourMarkerView(Context context, int layoutResource) {
super(context, layoutResource);
tvContent = (TextView) findViewById(R.id.tvContent);
mainbackground = (RelativeLayout) findViewById(R.id.mainbackground);
}
// callbacks everytime the MarkerView is redrawn, can be used to update the
// content (user-interface)
#Override
public void refreshContent(Entry e, Highlight highlight) {
if(e!=null && e.getData()!=null){
Log.d("Yoyo",e.getData().toString());
mainbackground.setBackgroundColor(Color.parseColor(e.getData().toString().split(";")[1]));
tvContent.setText("" + e.getData().toString().split(";")[0]);
// this will perform necessary layouting
super.refreshContent(e, highlight);
}
}
private MPPointF mOffset;
#Override
public MPPointF getOffset() {
if(mOffset == null) {
// center the marker horizontally and vertically
mOffset = new MPPointF(-(getWidth() / 2), -getHeight());
}
return mOffset;
}
}
Below is code for Chart:
chart.getDescription().setEnabled(false);
chart.setBackgroundColor(Color.parseColor("#f9f9f9"));
chart.setDrawGridBackground(false);
chart.setDrawBarShadow(false);
chart.setHighlightFullBarEnabled(false);
// draw bars behind lines
chart.setDrawOrder(new CombinedChart.DrawOrder[]{
CombinedChart.DrawOrder.BAR, CombinedChart.DrawOrder.SCATTER
});
chart.getAxisRight().setEnabled(false);
chart.getAxisLeft().setEnabled(false);
chart.getXAxis().setEnabled(false);
Legend legend = chart.getLegend();
legend.setEnabled(false);
YourMarkerView mv = new YourMarkerView(myActivity, R.layout.custom_marker_view);
// Set the marker to the chart
mv.setChartView(chart);
chart.setMarker(mv);
chart.setDragEnabled(false);
chart.setScaleEnabled(false);
// force pinch zoom along both axis
chart.setPinchZoom(false);
// enable touch gestures
chart.setTouchEnabled(true);
CombinedData data = new CombinedData();
data.setData(generateBarData());
data.setData(generateScatterData());
chart.setData(data);
chart.invalidate();
private BarData generateBarData() {
ArrayList<BarEntry> entries1 = new ArrayList<>();
ArrayList<BarEntry> entries2 = new ArrayList<>();
for (int index = 0; index < count; index++) {
entries1.add(new BarEntry(0, getRandom(25, 25)));
// stacked
entries2.add(new BarEntry(0, new float[]{getRandom(13, 12), getRandom(13, 12)}));
}
BarDataSet set1 = new BarDataSet(entries1, "Bar 1");
set1.setColor(Color.rgb(60, 220, 78));
set1.setValueTextColor(Color.rgb(60, 220, 78));
set1.setValueTextSize(10f);
set1.setAxisDependency(YAxis.AxisDependency.LEFT);
BarDataSet set2 = new BarDataSet(entries2, "");
set2.setStackLabels(new String[]{"Stack 1", "Stack 2"});
set2.setColors(Color.rgb(61, 165, 255), Color.rgb(23, 197, 255));
set2.setValueTextColor(Color.rgb(61, 165, 255));
set2.setValueTextSize(10f);
set2.setAxisDependency(YAxis.AxisDependency.LEFT);
float groupSpace = 0.06f;
float barSpace = 0.02f; // x2 dataset
float barWidth = 0.45f; // x2 dataset
// (0.45 + 0.02) * 2 + 0.06 = 1.00 -> interval per "group"
BarData d = new BarData(set1, set2);
d.setBarWidth(barWidth);
// make this BarData object grouped
d.groupBars(0, groupSpace, barSpace); // start at x = 0
return d;
}
private ScatterData generateScatterData() {
ScatterData d = new ScatterData();
ArrayList<Integer> colors = new ArrayList<Integer>();
for (String color : details.getSequenceColors()) {
colors.add(Color.parseColor(color));
}
ArrayList<Entry> entries = new ArrayList<>();
for (float index = 0; index < count; index += 0.5f)
entries.add(new Entry(index + 0.25f, getRandom(10, 55),"title;"+colors.get(index)));
ScatterDataSet set = new ScatterDataSet(entries, "Scatter DataSet");
set.setDrawHorizontalHighlightIndicator(false);
set.setDrawVerticalHighlightIndicator(false);
set.setColors(colors);
set.setScatterShape(ScatterChart.ScatterShape.CIRCLE);
set.setScatterShapeSize(20f);
set.setDrawValues(false);
set.setValueTextSize(10f);
d.addDataSet(set);
return d;
}
details.getSequenceColors is simple pojo contains the list of colors. For each point on Scatter Graph i am setting different colors. I am setting ScatterShape.CIRCLE color and Marker Background color same on Scatter Graph. As per Draw order I am drawing the bar graph first then the scatter one. Issue here i am facing is When i click on area where no scatter points exist the marker background color and nearest scatter point color is different and it highlights Bar graph datapoint as well. Its doesnt show the exact marker on Scatter points not sure why. How can i make sure that the scatter Circle color and marker Background color will be always in sync for each data points?
Solved by Using Custom ScatterDataSet Class:
public class MyScatterDataSet extends ScatterDataSet {
static int currentIndex = 0;
public MyScatterDataSet(List<Entry> yVals, String label) {
super(yVals, label);
}
#Override
public int getColor(int index) {
int ret =super.getColor(currentIndex);
currentIndex+=1;
return ret;
}
}
I am trying to highlight the LimiteLine (upper and lower limits) just like shown in GitHub Pull Request: Highlight Axis #4477.
Below is the image used as an example:
And not only that, I would like to custom the rectangle black box that contains the highlighted values.
I would also like them to be fixed, I mean: I don't want them to disappear when the chart is touched, while showing the MarkerView for the other points on the graph.
But it's not clear to me how to achieve this result.
I am using MPAndroid version 3.1.0 and LineChart
I am creating my LineChart from the example shown in https://blog.csdn.net/a8688555/article/details/80344159:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_settings, container, false);
mLineChart = view.findViewById(R.id.settings_graph);
List<Entry> entries = new ArrayList<>();
for (int i = 0; i < 12; i++)
entries.add(new Entry(i, new Random().nextInt(300)));
LineDataSet dataSet = new LineDataSet(entries, "Label"); // add entries to dataset
dataSet.setDrawCircles(false);
dataSet.setColor(Color.parseColor("#7d7d7d"));
dataSet.setCircleColor(Color.parseColor("#7d7d7d"));
dataSet.setLineWidth(3f);
mLineChart.setScaleEnabled(false);
mLineChart.setExtraRightOffset(15f);
mLineChart.setExtraLeftOffset(30f);
LimitLine upper_limit = new LimitLine(dataSet.getYMax(), "Preco maximo");
upper_limit.setLineWidth(2f);
upper_limit.enableDashedLine(10f, 10f, 0f);
upper_limit.setLabelPosition(LimitLine.LimitLabelPosition.RIGHT_TOP);
upper_limit.setTextSize(15f);
LimitLine lower_limit = new LimitLine(dataSet.getYMin(), "Preco minimo");
lower_limit.setLineWidth(2f);
lower_limit.enableDashedLine(10f, 10f, 0f);
lower_limit.setLabelPosition(LimitLine.LimitLabelPosition.RIGHT_BOTTOM);
lower_limit.setTextSize(15f);
// Setup Y-Axis
YAxis rightAxis = mLineChart.getAxisRight();
// Disable Y-axis on the right
rightAxis.setEnabled(true);
// Disable Y grid lines
rightAxis.setDrawGridLines(false);
rightAxis.setValueFormatter(new ValueFormatter() {
#Override
public String getFormattedValue(float value) {
return super.getFormattedValue(value);
}
});
YAxis leftAxis = mLineChart.getAxisLeft();
// Disable Y-axis on the left
leftAxis.setEnabled(false);
leftAxis.setDrawGridLines(false);
rightAxis.setAxisMaximum(dataSet.getYMax() + (float) (dataSet.getYMax() * 0.1));
leftAxis.setAxisMaximum(dataSet.getYMax() + (float) (dataSet.getYMax() * 0.1));
// Set max and min values
rightAxis.removeAllLimitLines();
rightAxis.addLimitLine(upper_limit);
rightAxis.addLimitLine(lower_limit);
rightAxis.setDrawLimitLinesBehindData(true);
// Setup X-Axis
XAxis xAxis = mLineChart.getXAxis();
xAxis.setTextColor(Color.parseColor("#333333"));
xAxis.setTextSize(11f);
xAxis.setAxisMinimum(0f);
xAxis.setDrawAxisLine(true);
xAxis.setDrawGridLines(false);
xAxis.setDrawLabels(true);
xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
xAxis.setGranularity(1f);
String[] mValues = {"Jan", "Fev", "Mar", "Abr", "Mai", "Jun", "Jul", "Ago", "Set", "Out", "Nov", "Dez"};
xAxis.setValueFormatter(new ValueFormatter() {
#Override
public String getFormattedValue(float value) {
return mValues[(int) value];
}
});
// Transparent legend
Legend legend = mLineChart.getLegend();
legend.setForm(Legend.LegendForm.NONE);
legend.setTextColor(Color.WHITE);
mLineChart.setOnChartValueSelectedListener(new OnChartValueSelectedListener() {
#Override
public void onValueSelected(Entry e, Highlight h) {
Log.i(TAG, "onValueSelected: highlight is: "+h);
if (mLineChart.isMarkerAllNull()) {
Log.i(TAG, "onValueSelected: isMarkerAllNull()");
// adding the markers
createMakerView();
// highlight the custom marker
mLineChart.highlightValue(h);
}
}
#Override
public void onNothingSelected() {
}
});
// text on X-axis
Description description = new Description();
description.setEnabled(false);
mLineChart.setDescription(description);
// create objects on the chart
createMakerView();
//3. setup data
LineData lineData = new LineData(dataSet);
// Draw text over line
lineData.setDrawValues(false);
mLineChart.setData(lineData);
mLineChart.animateXY(1000, 500);
mLineChart.invalidate(); // refresh
// Inflate the layout for this fragment
return view;
}
public void createMakerView() {
DetailsMarkerView detailsMarkerView = new DetailsMarkerView(getContext());
detailsMarkerView.setChartView(mLineChart);
mLineChart.setDetailsMarkerView(detailsMarkerView);
mLineChart.setPositionMarker(new PositionMarker(getContext()));
mLineChart.setRoundMarker(new RoundMarker(getContext()));
}
The image below shows the result tha I am trying to achieve:
I appreciate any help!
I am using MPAndroidChart for plotting scatteredBarChart. The code is as follows:
Code:
public void setupScatteredBarChart(ArrayList<String> x, ArrayList<String> y1, ArrayList<String> y2 )
{
int maxYvalue = 0;
final String[] x_name = new String[x.size()];
for (int j = 0; j <x.size(); j++)
{
String[] temp = x.get(j).split("-");
x_name[j] = temp[0] + "/" + temp[1];
}
ArrayList<BarEntry> yVals1 = new ArrayList<BarEntry>();
for (int i = 0; i < x_name.length; i++)
{
float val1 = Float.parseFloat(y1.get(i));
float val2 = Float.parseFloat(y2.get(i));
yVals1.add(new BarEntry(i, new float[]{val1, val2},getResources().getDrawable(R.drawable.ic_launcher)));
float val_total = val1 + val2;
int I = (int) Math.ceil(val_total);
if (maxYvalue < I)
{
maxYvalue = I;
}
}
chart_scattered = (BarChart) findViewById(R.id.chart_scattered);
chart_scattered.setOnChartValueSelectedListener(Stat.this);
chart_scattered.getDescription().setEnabled(false);
chart_scattered.setMaxVisibleValueCount(40); // if more than 40 entries are displayed in the chart, no values will be drawn
chart_scattered.setPinchZoom(false); // scaling can now only be done on x- and y-axis separately
chart_scattered.setDrawGridBackground(false);
chart_scattered.setDrawBarShadow(false);
chart_scattered.setDrawValueAboveBar(false);
chart_scattered.setHighlightFullBarEnabled(false);
chart_scattered.setDoubleTapToZoomEnabled(false);
chart_scattered.setTouchEnabled(false);
chart_scattered.setFitBars(true);
chart_scattered.animateXY(800, 800);
chart_scattered.getAxisRight().setEnabled(false);
chart_scattered.getXAxis().setAxisMinimum(-0.5f); // adjust for showing first bar properly
// Left Y axis
YAxis leftAxis = chart_scattered.getAxisLeft(); // change the position of the y-labels
leftAxis.setAxisMinimum(0f); // this replaces setStartAtZero(true)
chart_scattered.getAxisLeft().setLabelCount(maxYvalue + 1, true);
chart_scattered.getAxisLeft().setAxisMinValue(0f);
chart_scattered.getAxisLeft().setValueFormatter(new MyYAxisValueFormatter());
// Bottom X axis
XAxis xLabels = chart_scattered.getXAxis();
xLabels.setPosition(XAxis.XAxisPosition.BOTTOM);
xLabels.setAxisMinimum(0f);
xLabels.setGranularity(1f);
xLabels.setValueFormatter(new IAxisValueFormatter() {
#Override
public String getFormattedValue(float value, AxisBase axis) {
return x_name[(int) value % x_name.length];
}
});
Legend l = chart_scattered.getLegend();
l.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM);
l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.RIGHT);
l.setOrientation(Legend.LegendOrientation.HORIZONTAL);
l.setDrawInside(false);
l.setFormSize(6f);
l.setFormToTextSpace(4f);
l.setXEntrySpace(6f);
BarDataSet set1;
if (chart_scattered.getData() != null && chart_scattered.getData().getDataSetCount() > 0)
{
set1 = (BarDataSet) chart_scattered.getData().getDataSetByIndex(0);
set1.setValues(yVals1);
chart_scattered.getData().notifyDataChanged();
chart_scattered.notifyDataSetChanged();
}
else
{
set1 = new BarDataSet(yVals1, "");
set1.setDrawIcons(false);
set1.setColors(getColors());
set1.setStackLabels(new String[]{"A", "B"});
ArrayList<IBarDataSet> dataSets = new ArrayList<IBarDataSet>();
dataSets.add(set1);
BarData data = new BarData(dataSets);
data.setValueTextColor(Color.WHITE);
chart_scattered.setData(data);
}
chart_scattered.invalidate();
}
Screen Capture:
Question:
How could the first Bar to be showing properly? I have researched a lot and added the following to the code but is still not successful as showing in the screen capture above.
chart_scattered.getXAxis().setAxisMinimum(-0.5f);
chart_scattered.setFitBars(true);
As the date will go on increasing, could it set max 7 Bars and more than that, it has to be scrolled horizontally?
Thanks!
Question 1
remove this line from your code
xLabels.setAxisMinimum(0f);
will solve your problem.
Question 2
To only show the first 7 bars, use this..
chart_scattered.setVisibleXRangeMaximum(7f);
but this will not allow the user to scroll horizontally yet, if you want to enable scrolling, you'll have to remove this line from your code
chart_scattered.setTouchEnabled(false);
I am assuming you used the above line so the user can't highlight the bars. To keep that behavior, use this function..
chart_scattered.setHighlightPerTapEnabled(false);
mpandroidchart for my project,I want to the result just like the below image.I meet some question have long time. The first I want show the data is 11.23% ,but the project show 11.2% for me ,I can't find any way to change it ,please help me .The second I want to the legend is like the below image,but the legent of mpandroidchart-barchar no have description, how can I do? The third question is that I want to change y axis like the below image, I don't know if it realize?
![I want image]: http://i.stack.imgur.com/tuXhb.png
![My image now]: http://i.stack.imgur.com/NG9FB.png
public class BarChartActivity extends Activity {
private BarChart barChart;
private BarData data;
private BarDataSet dataSet;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bar_chart);
barChart = (BarChart) findViewById(R.id.barchart);
barChart.getAxisRight().setEnabled(false); // 隐藏右边的y轴
barChart.getXAxis().setPosition(XAxisPosition.BOTTOM);
barChart.setGridBackgroundColor(Color.WHITE); // 设置背景色
barChart.getXAxis().setDrawGridLines(false); // 隐藏网格竖线
YAxis yAxis = barChart.getAxisLeft(); // 得到y轴坐标
yAxis.setStartAtZero(false); // y轴是否从0开始
yAxis.mAxisMinimum = -20f;
yAxis.setLabelCount(10); // x轴横线的条数
yAxis.setAxisMinValue(-100f); // 设置最小值
yAxis.setAxisMaxValue(99f);
// yAxis.setSpaceTop(100);
// yAxis.setSpaceBottom(-100);
// barChart.setVisibleYRange(50f,null);
// barChart.getXAxis().enableGridDashedLine(400, 50, 0);
// barChart.getAxisLeft().resetAxisMaxValue(); //自动调整y轴的最大值
// legend.setLabels(new String[]{"你好","我好","大家好"});
barChart.getLegendRenderer();
barChart.getXAxis().setAxisLineColor(Color.BLUE); // 设置x轴线的颜色
barChart.getAxisLeft().setAxisLineColor(Color.GREEN); // 设置y轴线的颜色
barChart.getAxisLeft().setGridColor(Color.RED); // x轴线的颜色
barChart.getAxisLeft().setGridLineWidth(1f); // x轴网格线的宽度
barChart.getAxisLeft().setSpaceTop(150f);
barChart.getAxisLeft().setTextColor(Color.RED);// y坐标轴的上的刻度文字的颜色
// List<String> list = new ArrayList<String>();
// list.add("你好");
// list.add("你好1");
// list.add("你好2");
// barChart.getLegend().setLabels(list);
Legend legend = barChart.getLegend();
legend.setXEntrySpace(5f);
legend.setYEntrySpace(20f);
barChart.getXAxis().setSpaceBetweenLabels(5);
barChart.getXAxis().setYOffset(2f);
barChart.getAxisLeft().setValueFormatter(new PercentFormatter());
ArrayList<BarEntry> entries = new ArrayList<BarEntry>();// 显示的条目
ArrayList<String> xVals = new ArrayList<String>(); // 横坐标标签
float[] yValues = getYValues(90.23f, -2.84f, 9.21f);
for (int i = 0; i < 3; i++) {
entries.add(new BarEntry(yValues[i], i));
xVals.add(""); // 可以从这里取消x轴的坐标
}
int[] colors = new int[] { Color.rgb(90, 147, 229),
Color.rgb(247, 183, 48), Color.rgb(245, 70, 70) };
dataSet = new BarDataSet(entries, ""); // 原来是公司你利润报表
dataSet.setColors(colors);
dataSet.setBarSpacePercent(70f); // 设置柱子的宽度
dataSet.setValueFormatter(new PercentFormatter()); // 设置柱子上的数字百分数显示
dataSet.setValueTextColor(Color.BLUE); // 柱子上数字的颜色
data = new BarData(xVals, dataSet);
barChart.setData(data);
barChart.animateY(3000);
barChart.setDescription("");// 公司前半年财务报表(单位:万元)
barChart.getLegend().setPosition(LegendPosition.BELOW_CHART_CENTER); // 设置图例在正下方
barChart.getLegend().setStackSpace(50f); // 设置图例之间的距离
dataSet.setValueTextSize(28); // 设置柱子上数字的大小
}
public float[] getYValues(float x, float y, float z) {
return new float[] { x, y, z };
}
}
For number format you set ValueFormatter.
You can set Legend property like Style color, font etc using Legend.
To change Y axis negative use setStartAtZero(false);
So I'm using the awesome MPAndroid Chart library to make a simple LineChart. I was able to customize it heavily using the example project on GitHub.
The problem is, when I move it to my own code, certain methods are no longer able to be resolved:
mLineChart.setExtraOffsets() and mLineChart.setAutoScaleMinMaxEnabled() in particular. There might be others but these are the only two I've noticed.
Everything else works fine though. Any idea why I can't access these two methods? What should I dig into to find out more about why this is the case?
public class MyFragment extends Fragment {
private LineChart mLineChart;
// stuff here
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// stuff here
// Creating numbers line chart for candidate
LineChart numChart = (LineChart)view.findViewById(R.id.numbersLineChart);
setNumChart(numChart, mObject.getNums());
// stuff here
}
public void setNumChart(LineChart lineChart, List<Integer> nums){
mLineChart = lineChart;
mLineChart.setDrawGridBackground(false);
// no description text
mLineChart.setDescription("");
mLineChart.setNoDataTextDescription("You need to provide data for the chart.");
// enable value highlighting
mLineChart.setHighlightEnabled(true);
// enable touch gestures
mLineChart.setTouchEnabled(true);
// enable scaling and dragging
mLineChart.setDragEnabled(false);
mLineChart.setScaleEnabled(false);
// if disabled, scaling can be done on x- and y-axis separately
mLineChart.setPinchZoom(false);
// create a custom MarkerView (extend MarkerView and specify the layout to use for it)
MyMarkerViewv2 mv = new MyMarkerViewv2(getActivity(), R.layout.custom_marker_view, mLineChart);
// set the marker to the chart
mLineChart.setMarkerView(mv);
// disable all axes lines and labels
YAxis leftAxis = mLineChart.getAxisLeft();
leftAxis.setEnabled(false);
mLineChart.getAxisRight().setEnabled(false);
XAxis bottomAxis = mLineChart.getXAxis();
bottomAxis.setEnabled(false);
// add data
setLineChartData(nums);
//THIS METHOD CANNOT BE RESOLVED********************
mLineChart.setExtraOffsets(30f,50f,30f,0f);
// get the legend (only possible after setting data)
Legend l = mLineChart.getLegend();
l.setEnabled(false);
mLineChart.invalidate();
}
public void setLineChartData(List<Integer> nums){
//create xVariables aka strings of the months
ArrayList<String> xVals = new ArrayList<String>();
for (int i = 0; i < nums.size(); i++) {
xVals.add(Month.getMonthfromIndex(i).getAbbrev());
}
//add corresponding numbers
ArrayList<Entry> yVals = new ArrayList<Entry>();
for (int i = 0; i < nums.size(); i++) {
yVals.add(new Entry(nums.get(i), i));
}
// create a dataset and give it a type
LineDataSet set1 = new LineDataSet(yVals, "DataSet");
set1.setColor(Color.BLACK);
set1.setCircleColor(Color.BLACK);
set1.setLineWidth(0.75f);
set1.setDrawCircles(true);
set1.setDrawValues(false);
set1.setCircleSize(1.75f);
set1.setDrawCircleHole(false);
ArrayList<LineDataSet> dataSets = new ArrayList<LineDataSet>();
dataSets.add(set1); // add the datasets
// create a data object with the datasets
LineData data = new LineData(xVals, dataSets);
// set data
mLineChart.setData(data);
}
// stuff here
class MyMarkerViewv2 extends MarkerView {
private TextView markerContent;
private LineChart mChart;
public MyMarkerViewv2(Context context, int layoutResource, LineChart lChart) {
super(context, layoutResource);
mChart = lChart;
markerContent = (TextView) findViewById(R.id.markerContent);
}
// callbacks everytime the MarkerView is redrawn, can be used to update the
// content (user-interface)
#Override
public void refreshContent(Entry e, int dataSetIndex) {
if (e instanceof CandleEntry) {
CandleEntry ce = (CandleEntry) e;
List<String> months = mChart.getLineData().getXVals();
markerContent.setText(months.get(e.getXIndex() % 12) + "\n" + Utils.formatNumber(ce.getHigh(), 0, true) + "%");
} else {
List<String> months = mChart.getLineData().getXVals();
markerContent.setText(months.get(e.getXIndex() % 12) + "\n" + Utils.formatNumber(e.getVal(), 0, true) + "%");
}
}
#Override
public int getXOffset() {
// this will center the marker-view horizontally
return -(getWidth() / 2);
}
#Override
public int getYOffset() {
// this will cause the marker-view to be above the selected value
return -getHeight();
}
}
I also have the LineChart wrapped inside a vertical LinearLayout with other elements and that whole thing wrapped inside a ScrollView. Not sure if that's what's causing the problem or not.
Nevermind, I figured it out. It's because the library downloaded by Maven and Gradle is not exactly the same as the one included in the example project on the website.