PhilJay / MPAndroidChart

A powerful 🚀 Android chart view / graph view library, supporting line- bar- pie- radar- bubble- and candlestick charts as well as scaling, panning and animations.
Other
37.53k stars 9.01k forks source link

Date on X axis. #789

Closed joshisunil-1983 closed 9 years ago

joshisunil-1983 commented 9 years ago

hi, i am using MPandroid chart in my app. i want to plot chart using values on y axis and date on x axis. I don't find any datetime axis in mp android chart. is there any way to plot x axis using date. i have values against date. i want to show the dates in (ddMMM-yy) format on x axis and the values on y axis. anyone can pass me the sample link for the same.

sample for data: Date(X axis) Value(Y axis) 01/01/2001 966.78 01/02/2001 666.78 01/03/2001 966.78 01/04/2001 966.78 01/05/2001 966.78 01/06/2001 966.78 01/07/2001 966.78

guide.

dongorias commented 5 years ago

@CG-Vivek Okay thank you so much

CG-Vivek commented 5 years ago

above are 1Day, 1 Week, 1 Month

dongorias commented 5 years ago

@CG-Vivek That's exactly what I want to do

dongorias commented 5 years ago

@CG-Vivek Is it possible for you to make available the part of the code that handles this part?

CG-Vivek commented 5 years ago

sorry, won't be able to share code snapshot. you can identify chart for 1day, 1week, 1month and accordingly create an array of xaxisData with particular date formatter for eg: 1Day (date formatter) : "hh:mm" 1week(date formatter): "dd/mm/yyy hh:mm" 1month(date formatter): "dd/mmm/yyyy"

dongorias commented 5 years ago

@CG-Vivek Thank you very much for the help

miz33ar commented 5 years ago

Note: below solution was implemented using the following version:

compile 'com.github.PhilJay:MPAndroidChart:v3.0.0-beta1'

This workaround is based on the implementation of "DayAxisValueFormatter.java" suggested previously by @PhilJay. Final result looks like this:

screenshot

Steps:

1. Expressing x values in timestamps:

Say, for example, we have this data set:

x y 2016-01-01 15:00:00 GMT 25 2016-01-01 22:00:00 GMT 58 2016-01-02 08:00:00 GMT 36 2016-01-02 14:00:00 GMT 12 2016-01-02 19:00:00 GMT 29 We would like to populate a MPAndroidChart LineChart instance with above date set but we can only do so using a float type in the form: Entry(float x, float y). One easy way to handle this obstacle is to convert all dates to timestamps to get this result:

x y 1451660400 25 1451685600 58 1451721600 36 1451743200 12 1451761200 29 Now, it seems like we should be good to go but one final adjustment is still required. When I tried these huge x values, my chart became really slow especially when zooming in and out.

2. Converting timestamps to small numbers:

As a solution to this, we can further manipulate these x values by using this conversion:

Xnew = Xold - reference_timestamp

  • Xnew: timestamp after conversion
  • Xold: original timestamp
  • reference_timestamp: first timestamp in our sorted data set in ascending order.

First timestamp in a sorted data set should be the minimum timestamp which can be perfectly used as a zero reference. In that case, if we apply this equation to our sorted data set such as:

reference_timestamp = 1451660400

we get this new data set:

x y 0 25 25200 58 61200 36 82800 12 100800 29

We can even reduce these numbers by converting from seconds timestamps to minutes timestamps if that is really needed.

Make sure to keep reference_timestamp stored in a global variable so that you can retrieve your original timestamp when needed.

3. Applying ValueFormatter to show x labels of hours and minutes:

At this moment, your chart should be working smoothly but your x axis will show labels that has no meaning to your user. Let's add some meaning to our x axis by using this value formatter which provides a nice label to our dataset in hours and minutes (HH:mm): HourAxisValueFormatter.java

You can apply it in this way:

AxisValueFormatter xAxisFormatter = new HourAxisValueFormatter(referenceTimestamp);
XAxis xAxis = mChart.getXAxis();
xAxis.setValueFormatter(xAxisFormatter);

4. Set a MarkerView to show a popup containing the full date and time when a value is highlighted:

More details about MarkerView can be found here wiki.

Use MyMarkerView.java to show full date and time when a value is pressed. Implementation is easy just call setMakerView() like this:

MyMarkerView myMarkerView= new MyMarkerView(getApplicationContext(), R.layout.my_marker_view_layout, referenceTimestamp);
mChart.setMarkerView(myMarkerView);

R.layout.my_marker_view_layout is found here: custom_marker_view.xml and @drawable/marker2 is found here: marker2.png

how do i converts date to timestamps??

dongorias commented 5 years ago

@miz33ar Hi, thank you very much for your approach, please you can give us access to the complete source code of this part?

miz33ar commented 5 years ago
     @DonGorias229  here is my code ` protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 temperature = new ArrayList<>();
 temps = new ArrayList<>();// temps is a list of dates
 humidité = new ArrayList<>();
 entries = new ArrayList<Entry>();
 final LineChart chart = findViewById(R.id.chart);
 PerformNetworkRequestD request = new PerformNetworkRequestD(Api.url, new PerformNetworkRequestD.AsyncResponse() {
     @Override
     public void processFinish(JSONArray output) {
         if (output != null) {
             for (int i = 0; i < output.length(); i++) {
                 try {
                     int t = output.getJSONObject(i).getInt("nbTemp");
                     String d = output.getJSONObject(i).getString("le_temps");
                     int h = output.getJSONObject(i).getInt("humidite");
                     temperature.add(t);
                     humidité.add(h);

                     Date date = formatter.parse(d);

                     temps.add(date);

                 } catch (JSONException e) {
                     e.printStackTrace();
                 } catch (ParseException e) {
                     e.printStackTrace();
                 }
             }
             //write your code here
                for(int i=0;i<temperature.size();i++){

                    entries.add(new Entry(temps.get(i),temperature.get(i))); //here is the issue ENTRY accept only float 

                }
                LineDataSet dataSet = new LineDataSet(entries, "temperature");
                LineData lineData = new LineData(dataSet);
                chart.setData(lineData);
                chart.invalidate();`
dongorias commented 5 years ago

@miz33ar thank you very much, may I have your email address?

miz33ar commented 5 years ago

@miz33ar Hi, thank you very much for your approach, please you can give us access to the complete source code of this part?

@miz33ar Hi, thank you very much for your approach, please you can give us access to the complete source code of this part?

i added my code can you pls check -- above

dongorias commented 5 years ago

@miz33ar Yes, I did, but I have a particular concern that I would like to discuss with you privately

miz33ar commented 5 years ago

Can you show me how put my list of dates on x axis pls ?? and what you want to discuss im all yours .

Provenance : Courrierhttps://go.microsoft.com/fwlink/?LinkId=550986 pour Windows 10


De : Don Arias notifications@github.com Envoyé : Monday, April 29, 2019 3:24:01 PM À : PhilJay/MPAndroidChart Cc : miz33ar; Mention Objet : Re: [PhilJay/MPAndroidChart] Date on X axis. (#789)

@miz33arhttps://github.com/miz33ar Yes, I did, but I have a particular concern that I would like to discuss with you privately

— You are receiving this because you were mentioned. Reply to this email directly, view it on GitHubhttps://github.com/PhilJay/MPAndroidChart/issues/789#issuecomment-487599887, or mute the threadhttps://github.com/notifications/unsubscribe-auth/AL6JR5JFXELML3APGDPQZCDPS4AIDANCNFSM4BJA52LQ.

miz33ar commented 5 years ago

@miz33ar thank you very much, may I have your email address?

zaeriaanas@outlook.fr

dongorias commented 5 years ago

@ miz33ar merci beaucoup, puis-je avoir votre adresse e-mail?

zaeriaanas@outlook.fr

thank you very much, I would leave a message by mail

miz33ar commented 5 years ago

@ miz33ar merci beaucoup, puis-je avoir votre adresse e-mail?

zaeriaanas@outlook.fr

thank you very much, I would leave a message by mail

Hi,im still waiting for your message ,i realy need your help @DonGorias229 ..

ghost commented 5 years ago

Now possible:

https://github.com/PhilJay/MPAndroidChart/blob/master/MPChartExample/src/com/xxmassdeveloper/mpchartexample/BarChartActivity.java

Example formatter:

https://github.com/PhilJay/MPAndroidChart/blob/master/MPChartExample/src/com/xxmassdeveloper/mpchartexample/custom/DayAxisValueFormatter.java

both link broken.

sidcgithub commented 5 years ago

The following are tips to format date for candlestick graphs

1) Use IAxisValueFormatter IAxisValueFormatter theFormatYouWant= new TheFormatYouWant();

2) Create a formatter by implementing IAxisValueFormatter

public class TheFormatYouWant implements IAxisValueFormatter {
    @Override
    public String getFormattedValue(float value, AxisBase axis) {

        Date date = new Date((long)value);
        //Specify the format you'd like
        SimpleDateFormat sdf = new SimpleDateFormat("MM/dd", Locale.ENGLISH);
        return sdf.format(date);

    }
}

3) Set Format to XAxis After yValsCandleStick.add(timestamp, float1, float2, foat3, float4);

Set the format for the timestamps


 XAxis xAxis = candleStickChart.getXAxis();
 xAxis.setValueFormatter(theFormatYouWant);

The above works with the following dependencies

    implementation 'com.github.PhilJay:MPAndroidChart-Realm:v3.0.3@aar'
    implementation 'com.github.PhilJay:MPAndroidChart:v3.0.3'

Edited A more concise example provided here https://github.com/PhilJay/MPAndroidChart/wiki/Setting-Data

ghost commented 4 years ago

Hey!

I got a problem similar to this. I have data in Firestore database and I am trying to show it a line chart. I want HH:mm on m y xAxis and temperature values on yAxis. I have the 3.1.0 version and I am trying to work with HourAxisValueFormatter. I have converted the x values from date objects and then I turned them according @Yasir-Ghunaim instructions, but I only get the first time "08:00" to my xAxis and I can't figure out how to get them all. I have the <xnew values in a Long type arraylist.

I also tried this in fdw other ways and managed to get xAxis correctly but then I could not get my entries correctly -> could not put my values to the correct x-indexes.

Can someone help me?

Proxcentaur commented 4 years ago

@JonesiL could u tell me how to convert the x values from the date object?

KonstantinDementiev commented 4 years ago

Maybe this is useful to someone. To round timestamps on the x-axis do the following in ValueFormatter: long dateInMillis = (long) Math.round ((value * 60000) / 300000) * 300000; value - Unix time in milliseconds. This will round the marks up to 5 minutes and remove the uneven marks: before: 5.01, 6.01, 6.58... after: 5.00, 6.00, 7.00...

trav3711 commented 3 years ago

I'm so confused by this. I have a DB containing SQLite timestamps and integer values. All I want to do is create one bar for each timestamp/value entry. Therefore I just want one bar per entry, and I don't know why I have to mess around with all of this Value Formatter stuff.

JerryThl commented 2 years ago

My problem happened on Candlestick chart whereby the bar will disappear when using IndexAxisValueFormatter method.

The simplest way is to divide the timestamp by 10k or 100k, ONLY THEN pass into IndexAxisValueFormatter Within IndexAxisValueFormatter, multiply the received timestamp by 10k or 100k depending which amount you divide previously.

Problem Solved.