I have a lineGraph with float values on both x-axis and y-axis? My question is that how can i set String values on x-axis like date or name of months.I am using GraphView-3.0.jar library.my code is
values_list.add(1.0);
values_list.add(5.0);
values_list.add(9.0);
values_list.add(12.0);
values_list.add(17.0);
values_list.add(1.0);
values_list.add(13.0);
values_list.add(23.0);
graphData = new GraphViewData[(values_list.size())];
double price_copy = 0;
for (int i = 0; i < values_list.size(); i++) {
price_copy = values_list.get(i);
graphData[i] = new GraphViewData(i, price_copy);
}
GraphView graphView;
graphView = new LineGraphView(this // context
, "" );// graphView.addSeries(exampleSeries);// data
graphView.addSeries(new GraphViewSeries("values",
new GraphViewStyle(Color.rgb(00, 00, 128), 3),
graphData));
graphView.setShowLegend(true);
// set view port, start=2, size=40
graphView.setViewPort(0, 10);
graphView.setScalable(true);
graphView.setScrollable(true);
LinearLayout layout = (LinearLayout) findViewById(R.id.LNL_CHART);
layout.addView(graphView);
Also i have no idea about AchartEngine,thanks in advance.
Use achart engine library. you can search for that on google. it helped me.Thanks
Just use the label formatter. You could store your x-labels as string in an array.
For example:
final String[] xLabels = new String[] {
"foo", "bar", "third", "bla", "more"
};
GraphView graphView = new LineGraphView(this, "example") {
#Override
protected String formatLabel(double value, boolean isValueX) {
if (isValueX) {
return xLabels[(int) value];
} else {
// return y label as number
return super.formatLabel(value, isValueX); // let the y-value be normal-formatted
}
}
};
Related
i am using MPAndroidChart barchart ... every thing is okay except the x-axis... my bars are not aligned properly on labels. when i zoome the chart then bars come on its labels but that zoom is not what i wanted and also when i zooming the labels repeat until next and so on.
my data is like eg:
age(x) weight(y)
2 90
5 100
7 200
10 300
the age is my labels and it is string type ... i need it to be string label.
this is what i got
this is my code in c#
//-----chart-------------
barChart = FindViewById<BarChart>(Resource.Id.barChart);
List<BarEntry> entries = new List<BarEntry>();
List<string> labelz = new List<string>();
int c = 0;
foreach(var rec in weighting_lst)
{
entries.Add(new BarEntry(c, rec.Weight));
labelz.Add(rec.Age.ToString());
c++;
}
BarDataSet dataset = new BarDataSet(entries, "وزن به گرم");
BarData data = new BarData(dataset);
var xdata = barChart.XAxis;
xdata.ValueFormatter = new MyLabelFormatter(labelz);
xdata.SetCenterAxisLabels(false);
barChart.Data = data;
barChart.SetScaleEnabled(true);
barChart.SetFitBars(true);
public class MyLabelFormatter : Java.Lang.Object, IAxisValueFormatter
{
//private string[] customLabels = new string[] { "A", "B", "C", "D", "E", "F" };
public List<string> label_lst = new List<string>();
public MyLabelFormatter(List<string> _label_lst)
{
label_lst = _label_lst;
}
public string GetFormattedValue(float value, AxisBase axis)
{
return label_lst[(int)value % label_lst.Count];
}
}
for x position of bar entry i just use integer called c which increases by 1 on each loop so it gives me like 0f,1f,2f,......
i added xdata.Granularity = 1f; and it works for me .... xdata is my Xaxis
I created a graph app using MP android chart, i used it to plot two different line data sets . But my problem is that the value labels for the xaxis appear on the top of the graph . I need a way to make it to the bottom . below is my code
final LineChart linechart = (LineChart)findViewById(R.id.idlinechart);
//created list enties to hold the values
List<Entry> valuesCompany1 = new ArrayList<>(); List<Entry> valuesCompany2 = new ArrayList<>();
//created entry values to be entered into the lsit entry b
Entry c1e1 = new Entry(0f, 100000f); valuesCompany1.add(c1e1);
Entry c1e2 = new Entry (1f, 140000f);valuesCompany1.add(c1e2);
Entry c1e3 = new Entry(2f,90000f);valuesCompany1.add(c1e3);
Entry c1e4 = new Entry (3f, 150000f); valuesCompany1.add(c1e4);
Entry c2e1 = new Entry(0f, 50000f); valuesCompany2.add(c2e1);
Entry c2e2 = new Entry (1f, 50000f);valuesCompany2.add(c2e2);
Entry c2e3 = new Entry(2f,150000f);valuesCompany2.add(c2e3);
Entry c2e4 = new Entry (3f, 110000f); valuesCompany2.add(c2e4);
//so now we create line data to hold the list
LineDataSet linedatasetComp1 = new LineDataSet(valuesCompany1, "company 1");
linedatasetComp1.setAxisDependency(YAxis.AxisDependency.LEFT);
linedatasetComp1.setColor(Color.BLUE);
LineDataSet linedatasetComp2 = new LineDataSet(valuesCompany2, "company 2");
linedatasetComp2.setAxisDependency(YAxis.AxisDependency.LEFT);
linedatasetComp2.setColor(Color.RED);
List<ILineDataSet> iLinedata = new ArrayList<ILineDataSet>();
iLinedata.add(linedatasetComp1); //adding the line data sets into the line data list
iLinedata.add(linedatasetComp2);
//setting the Ilinedata list into line data
LineData linedata = new LineData(iLinedata);
//setting the line data into line chart
linechart.setData(linedata);
linechart.invalidate(); //refreshing the line chart
//Saving the picture to galery
Button savebutton = (Button)findViewById(R.id.button);
savebutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
linechart.saveToGallery("new Line chart", 150);
Toast.makeText(getApplicationContext(), "graph saved ", Toast.LENGTH_LONG).show();
}
});
final String[] Quaters = {"Q1", "Q2", "Q3", "Q4"};
IAxisValueFormatter valueFormater = new IAxisValueFormatter() {
#Override
public String getFormattedValue(float value, AxisBase axis) {
return Quaters[(int) value];
}
#Override
public int getDecimalDigits() {
return 0;
}
};
XAxis xAxis = linechart.getXAxis();
xAxis.setGranularity(1f);
xAxis.setValueFormatter(valueFormater);
Description desc = new Description();
desc.setText("A graph comparing revenuews of two companies ");
desc.setEnabled(true);
desc.setPosition(0,0);
desc.setTextColor(Color.BLACK);
linechart.setDescription(desc);
I don't know if LineChart has that option, but in case it does you just have to get the XAxis adjust the Position like this:
linechart.getXAxis().setPosition(XAxis.XAxisPosition.BOTTOM);
Hope it helps!
Use MPAndroid chart version 2.2.4 or above and use the code
mChart.getXAxis().setPosition(XAxis.XAxisPosition.BOTTOM);
as said by Ponchotg
I am using PhilJay/MPAndroidChart library in my app and I'd like to know if 2 things are possible:
to show the last 14 days and then scroll for previous days?
Can the dates (currently on the top of the graph) be moved to the bottom, along the x axis?
Here is the current pic from the app and where i want to move date
my method:
private void populateGraph(Cursor data) {
ArrayList<Entry> cravingsPoints = new ArrayList<Entry>();
ArrayList<Entry> severityPoints = new ArrayList<Entry>();
ArrayList<String> dates = new ArrayList<String>();
int index = 0;
for (int i = 0; i < data.getCount(); i++) {
if (i == 0) {
// if orientation changed we need to start from the first one again
data.moveToFirst();
} else {
data.moveToNext();
}
try {
String date = data.getString(data.getColumnIndex(SmokeFreeContentProvider.DIARY_DATE));
int cravings = data.getInt(data.getColumnIndex(SmokeFreeContentProvider.DIARY_CRAVINGS_COUNT));
int severity = data.getInt(data.getColumnIndex(SmokeFreeContentProvider.DIARY_CRAVINGS_SEVERITY));
DateTime diaryEntry = DateTimeFormat.forPattern("yyyyMMdd").parseDateTime(date);
String entryLabel = diaryEntry.toString("dd MMM");
cravingsPoints.add(new Entry(cravings, index));
severityPoints.add(new Entry(severity, index));
dates.add(entryLabel);
index++;
} catch (Exception e) {
Log.e("SmokeFreeCravingsGraph", e.getMessage(), e);
}
}
LineDataSet cravingsLineData = new LineDataSet(cravingsPoints, getString(R.string.cravings));
LineDataSet severityLineData = new LineDataSet(severityPoints, getString(R.string.severity));
cravingsLineData.setCircleSize(4f);
cravingsLineData.setLineWidth(6f);
cravingsLineData.setColor(getResources().getColor(R.color.green));
severityLineData.setCircleSize(4f);
severityLineData.setLineWidth(6f);
severityLineData.setColor(getResources().getColor(android.R.color.holo_blue_light));
ArrayList<LineDataSet> dataSets = new ArrayList<LineDataSet>();
dataSets.add(cravingsLineData);
dataSets.add(severityLineData);
Paint infoPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
infoPaint.setTextAlign(Paint.Align.CENTER);
infoPaint.setTextSize(com.github.mikephil.charting.utils.Utils.convertDpToPixel(14f));
infoPaint.setColor(getResources().getColor(R.color.dark_grey));
mChart.setDrawGridBackground(false);
mChart.setDrawYValues(false);
mChart.setDescription("");
mChart.setStartAtZero(true);
mChart.setPaint(infoPaint, Chart.PAINT_INFO);
mChart.setNoDataText(getString(R.string.no_cravings_info));
mChart.setNoDataTextDescription(getString(R.string.no_cravings_full_info));
mChart.setData(new LineData(dates, dataSets));
}
Yes, check the documentation: Modifying the Viewport
Take a look at the setVisibleXRange(float xRange) method.
Yes, check the documentation: XAxis
Take a look at the xAxis.setPosition(...) method.
I want to plot a XY line graph with some double values on Y axis and some String values on X axis. But the XYSeries takes only double/long values. So,is there any way I can use a string array on the X axis?
Thanks for any suggestions.
code:
//fDates are strings
XYSeries fPriceseries = new XYSeries("Fuel prices");
for(int i=0;i<fDates.length;i++)
{
long fDate = Long.parseLong(fDates[i]);
fPriceseries.add(fDate, fPrice[i]);
}
XYSeries fMileageSeries = new XYSeries("Mileage");
for(int i=0;i<fDates.length;i++)
{
long fDate = Long.parseLong(fDates[i]);
fMileageSeries.add(fDate, fMileage[i]);
}
Use TimeSeries:
fDates as Date array
TimeSeries fPriceseries = new TimeSeries("Fuel prices");
for(int i=0;i<fDates.length;i++)
{
fPriceseries.add(fDates[i], fPrice[i]);
}
TimeSeries fMileageSeries = new TimeSeries("Mileage");
for(int i=0;i<fDates.length;i++)
{
fMileageSeries.add(fDates[i], fMileage[i]);
}
fDates as String array - Using SimpleDateFormat.
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
TimeSeries fPriceseries = new TimeSeries("Fuel prices");
for(int i=0;i<fDates.length;i++)
{
fPriceseries.add(sdf.parse(fDates[i]), fPrice[i]);
}
TimeSeries fMileageSeries = new TimeSeries("Mileage");
for(int i=0;i<fDates.length;i++)
{
fMileageSeries.add(sdf.parse(fDates[i]), fMileage[i]);
}
Referencies:
http://www.achartengine.org/content/javadoc/org/achartengine/model/TimeSeries.html
http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html
You cannot plot a graph using string on any axis.
Explanation:
When we plot a graph we compare two values... as in 3,5 or 7,22 or 12.3,10000..
Plotting string with respect to an integer or double,is like comparing apples and oranges.
So m sorry friend but its not possible.. unless you convert the string or create a reference for its contents..
I am working on Pie charts using AChartEngine library. Here I want to disable chart values to show on charts, but only those whose content value is 0.If anyone known this please share to me.
Codings:
pchart=ChartFactory.getPieChartView(this,buildCategoryDataset("Daily Basis", values),renderer);
re.addView(pchart);
}
}
BuildCategory Renderer:
protected DefaultRenderer buildCategoryRenderer(int[] colors) {
DefaultRenderer renderer = new DefaultRenderer();
renderer.setLabelsTextSize(10);
renderer.setLegendTextSize(15);
renderer.setShowLegend(true);
renderer.setExternalZoomEnabled(true);
renderer.setZoomEnabled(true);
renderer.setZoomButtonsVisible(true);
renderer.setShowAxes(true);
// renderer.setMargins(new int[] { 20, 30, 15, 0 });
for (int color : colors) {
SimpleSeriesRenderer r = new SimpleSeriesRenderer();
r.setColor(color);
renderer.addSeriesRenderer(r);
}
return renderer;
}
DataSet Here:
protected CategorySeries buildCategoryDataset(String title, double[] values) {
CategorySeries series = new CategorySeries(title);
int k = 0,year;
String str_year;
str_year=String.valueOf(Math.round(values[0]));
Log.i("Invent","Year"+str_year);
year=Integer.parseInt(str_year);
Log.i("Invent","YearInt"+year);
if(flag_val==1)
{
for(k=0;k<tot_yearno-1;k++)
{
if(values[k]==0)
{
series.add(0.0); /// Here some settings for display null value.But **here i Want to display nothing Only.**
}
else
series.add("" + year_first++, values[k]);
}
}
if(flag_val==0)
{
for (double value : values) {
if(value==0)
{
series.add("" + ++k, 0.0);
}
else
series.add("Day " + ++k, value);
}
}
return series;
}
}
What you are doing here:
if(values[k]==0)
{
series.add(0.0); /// Here some settings for display null value.But **here i Want to display nothing Only.**
}
else
series.add("" + year_first++, values[k]);
}
You should do it like this:
if(values[k] != 0) //or possibly (values[k] >= 0) since you cannot show negatives either
{
series.add("" + year_first++, values[k]);
}
EDIT: Try this then:
if(values[k]==0)
{
series.add("" + year_first++, new Double(0.0));
}
else
{
series.add("" + year_first++, new Double(values[k]));
}
If you do not wish to show 0 values, just don't add them to the dataset.
Look at the createDataSet in the PieChartView for an example - there they add the values with the label.
private staticPieDataSet createDataSet(){
DefaultPieDataset dataset = new DefaultPieDataset();
dataset.setValue("One", new Double(43.2));
}
Now when you add your own values (I am not sure how you do it, but I pass them through the bundle datatype and then extract them for the following method), you can just not add based on value:
private staticPieDataSet createDataSet(Double[] values, String[] labels){
DefaultPieDataset dataset = new DefaultPieDataset();
for(int i = 0; i < values.length; i++){
if (value[i] > 0)
dataset.setValue(labels[i], values[i]);
}
}
PS!!! I wouldn't recommend this by the way - your users may become confused as to why some data shows up and others do not - rather put the value in brackets with the label so they can see this value is 0.
Do it something like this way, before showing the Chart View as I have done for TimeChart
for(int i=0;i<selectedCollectionY.size();i++)
{
if(selectedCollectionY.get(i).equalsIgnoreCase("0"))
{
selectedCollectionY.remove(i);
selectedCollectionX.remove(i);
}
}
View mView = null;
mView = ChartFactory.getTimeChartView(GraphActivity.this, Line_Chart
.getLineDemoDataset(mSpinner.getSelectedItem().toString(),
selectedCollectionX, selectedCollectionY), Line_Chart
.getLineDemoRenderer(mSpinner.getSelectedItem().toString()),
"MMM dd");
mView.setLayoutParams(new LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
mLinearLayout.removeAllViews();
mLinearLayout.addView(mView);