¿Cambiar el color de la columna en función del valor del eje numérico proveniente de la lista enlazada a base de datos ?

Hola grupo Syncfusion

Me gustaría saber como cambiar el color de las columnas en función del valor de los ejes Y en codigo C#, el eje Y va de 0 a 100 y me gustaría hacer que el color de la barra cambie a verde si está por debajo de 29, amarillo entre 30 y 32, y si es mayor a 32 rojo.

De acuerdo a esto, el valor del eje Y, Proviene de una lista que está enlazada a una base de datos y no he podido obtener exito con la condicional ya que me pintan todas las barras de color verde al ponerle la condicional propuesta anteriormente.

Entonces quisiera saber si esto se puede hacer o que me pueda dar un ejemplo de como hacerlo ya que llevo mucho tiempo tratandolo de resolver 
 
Les agradezco muchisimo por su ayuda.
Les comparto mi codigo.

 


Attachment: EjemploSemaforo_6901c9b9.zip

6 Replies 1 reply marked as answer

SJ Suyamburaja Jayakumar Syncfusion Team July 13, 2020 06:08 PM UTC

Hi Harrison Hincapie Cardona, 
 
Greetings from Syncfusion. 
 
We can achieve your requirement (Changing column color based on Numerical axis value) by binding color Model to the CustomBrushes of chart series. We can set the specific color to the chart segment as like in the below code, 
 
C#: 
public ChartColorCollection Colors { get; set; } 
 
. . . .  
 
Colors = new ChartColorCollection(); 
            foreach (var item in viewModel.Data) 
            { 
                if (item.YValue <= 29) 
                    Colors.Add(Color.Green); 
                else if (item.YValue > 29 && item.YValue <=32) 
                    Colors.Add(Color.Yellow); 
                else if (item.YValue == 40) 
                { 
                    Colors.Add(Color.Red);  
                } 
            } 
. . . . 
           ColumnSeries Semaforo = new ColumnSeries();  
            Semaforo.ColorModel.Palette = ChartColorPalette.Custom; 
            Semaforo.ColorModel.CustomBrushes = Colors; 
            chart.Series.Add(Semaforo);  
 
Screenshot:  
 
 
Or  
Your requirement is changed the individual column segmented color based on Numerical axis value, please refer the below code snippet  
 
C#: 
Semaforo.ColorModel.Palette = ChartColorPalette.Custom; 
 
            ChartGradientColor gradientColor1 = new ChartGradientColor() { StartPoint = new Point(0.5, 0), EndPoint = new Point(0.5, 1) }; 
            ChartGradientStop stop1 = new ChartGradientStop() { Color = Color.Green, Offset = 0.29f }; 
            ChartGradientStop stop2 = new ChartGradientStop() { Color = Color.Yellow, Offset = 0.32f }; 
            ChartGradientStop stop3 = new ChartGradientStop() { Color = Color.Red, Offset = 1 }; 
            gradientColor1.GradientStops.Add(stop1); 
            gradientColor1.GradientStops.Add(stop2); 
            gradientColor1.GradientStops.Add(stop3); 
 
            ChartGradientColorCollection gradientColors = new ChartGradientColorCollection() 
            { 
                gradientColor1, 
            }; 
 
            Semaforo.ColorModel.CustomGradientColors = gradientColors; 
 
Screenshot: 
 
 
 
If your requirement doesn’t meet with that or we misunderstood your query, can you please update more details of your exact requirement. This will be helpful for us to investigate further and provide you a better solution at the earliest. 
 
Regards, 
Suyamburaja J. 


Marked as answer

HH Harrison Hincapie Cardona replied to Suyamburaja Jayakumar July 14, 2020 03:27 AM UTC

Hi Harrison Hincapie Cardona, 
 
Greetings from Syncfusion. 
 
We can achieve your requirement (Changing column color based on Numerical axis value) by binding color Model to the CustomBrushes of chart series. We can set the specific color to the chart segment as like in the below code, 
 
C#: 
public ChartColorCollection Colors { get; set; } 
 
. . . .  
 
Colors = new ChartColorCollection(); 
            foreach (var item in viewModel.Data) 
            { 
                if (item.YValue <= 29) 
                    Colors.Add(Color.Green); 
                else if (item.YValue > 29 && item.YValue <=32) 
                    Colors.Add(Color.Yellow); 
                else if (item.YValue == 40) 
                { 
                    Colors.Add(Color.Red);  
                } 
            } 
. . . . 
           ColumnSeries Semaforo = new ColumnSeries();  
            Semaforo.ColorModel.Palette = ChartColorPalette.Custom; 
            Semaforo.ColorModel.CustomBrushes = Colors; 
            chart.Series.Add(Semaforo);  
 
Screenshot:  
 
 
Or  
Your requirement is changed the individual column segmented color based on Numerical axis value, please refer the below code snippet  
 
C#: 
Semaforo.ColorModel.Palette = ChartColorPalette.Custom; 
 
            ChartGradientColor gradientColor1 = new ChartGradientColor() { StartPoint = new Point(0.5, 0), EndPoint = new Point(0.5, 1) }; 
            ChartGradientStop stop1 = new ChartGradientStop() { Color = Color.Green, Offset = 0.29f }; 
            ChartGradientStop stop2 = new ChartGradientStop() { Color = Color.Yellow, Offset = 0.32f }; 
            ChartGradientStop stop3 = new ChartGradientStop() { Color = Color.Red, Offset = 1 }; 
            gradientColor1.GradientStops.Add(stop1); 
            gradientColor1.GradientStops.Add(stop2); 
            gradientColor1.GradientStops.Add(stop3); 
 
            ChartGradientColorCollection gradientColors = new ChartGradientColorCollection() 
            { 
                gradientColor1, 
            }; 
 
            Semaforo.ColorModel.CustomGradientColors = gradientColors; 
 
Screenshot: 
 
 
 
If your requirement doesn’t meet with that or we misunderstood your query, can you please update more details of your exact requirement. This will be helpful for us to investigate further and provide you a better solution at the earliest. 
 
Regards, 
Suyamburaja J. 


Hola amigo muchas gracias por su respuesta.

Que pena la molestia Pero lo que pasa es que segun su respuesta lo que entiendo en el foreach es que los datos vienen de un viewModel y yo no tengo un viewModel, la Data mia viene de un servicio web que va y consulta un procedimiento y me trae la información a la aplicación:

por medio de la siguiente URL:    cadena de const privado UrlSemaforos = "https://speedytools.telefonica.com.co:8080/MyWebService.svc/indicadorTransversaltipoIndicador=Transversales&direccionCompany=TI&nombreIndicador=SEMAFORO&detalle&ndicam=incánsos

contenido var = esperar cliente. GetAsync (UrlSemaforos);
                var json = content.Content.ReadAsStringAsync (). Resultado;

                    
                if (content.IsSuccessStatusCode)
                {

                    List <TableroTicketsDataContract> post = JsonConvert.DeserializeObject <List <TableroTicketsDataContract>> (json);

                    SemeforoVO semeforoVO;
                    List <SemeforoVO> listSemeforoVO = new List <SemeforoVO> ();

                    foreach (TableroTicketsDataContract i en la publicación)
                    {
                        semeforoVO = nuevo SemeforoVO ();
                        semeforoVO.periodo = i.periodo;
                        semeforoVO.meta = Convert.ToDouble (i.meta);
                        semeforoVO.numerador = Convert.ToDouble (i.numerador);
                        listSemeforoVO.Add (semeforoVO);

                    }

luego construyo la grafica.

SfChart chart = new SfChart();
                    SfChart graficaSemaforo = new SfChart();
                    graficaSemaforo.Title.Text = "Semáforos";

                    CategoryAxis primaryAxisSemaforo = new CategoryAxis();                   
                    graficaSemaforo.PrimaryAxis = primaryAxisSemaforo;
                    primaryAxisSemaforo.MajorGridLineStyle.StrokeColor = Color.Transparent;
                   
                    //primaryAxisSemaforo.Title.Text = "Valor indicador";

                    NumericalAxis secondAxisSemaforo = new NumericalAxis() { Minimum = 0, Maximum = 80 };                   
                    //secondAxisSemaforo.Title.Text = "Valor Indicador";
                    graficaSemaforo.SecondaryAxis = secondAxisSemaforo;                  
                    secondAxisSemaforo.MajorGridLineStyle.StrokeColor = Color.Transparent;
                    graficaSemaforo.SecondaryAxis.IsVisible = false;                    

                    ColumnSeries Semaforo = new ColumnSeries();
                    //Semaforo.IsTransposed = true;
                    Semaforo.ItemsSource = listSemeforoVO;
                    Semaforo.XBindingPath = "periodo";
                    Semaforo.YBindingPath = "numerador";                    
                    Semaforo.Label = "cantidad";
                    Semaforo.CornerRadius = new ChartCornerRadius(30);
                    Semaforo.Color = Color.FromHex("#21c7d8");
                    Semaforo.EnableAnimation = true;
                    Semaforo.AnimationDuration = 0.8;
                    Semaforo.DataMarker = new ChartDataMarker();
                    Semaforo.EnableTooltip = true;                    
                    Semaforo.SelectedDataPointColor = Color.FromHex("#62e7ff");
                    Semaforo.DataMarker.LabelStyle.TextColor = Color.FromHex("#ffffff");
                    Semaforo.DataMarker.LabelStyle.LabelPosition = DataMarkerLabelPosition.Inner;
                    Semaforo.DataMarker.LabelStyle.FontSize = 13;
                    Semaforo.EnableDataPointSelection = true;
                    Semaforo.ColorModel.Palette = ChartColorPalette.Custom;
                    Semaforo.ColorModel.CustomBrushes = Colors;
                    //Semaforo.DataMarker.LabelStyle = new DataMarkerLabelStyle() { LabelFormat = "{#}" };



---------------------------------------------------------------------------------------------------------------------------
este es el if que hice para traer los datos de la url y hacer la validacion segun su valor:


 foreach (TableroTicketsDataContract i in post)

                    {                                        

                        if (Convert.ToDouble(i.numerador) <= 29)
                           {
                             Semaforo.DataMarker.LabelStyle.BackgroundColor = Color.Green;                            

                        }
                        else if (Convert.ToDouble(i.numerador) > 29
                             && (Convert.ToDouble(i.numerador) <= 32))
                        {                            
                            Semaforo.DataMarker.LabelStyle.BackgroundColor = Color.Yellow;
                        }
                        else
                        {                         
                              Semaforo.DataMarker.LabelStyle.BackgroundColor = Color.Red;
                        }
                    }


pero este if me pinta la grafica todas de verde es decir todas se van por la primera validacion del if y hay se queda.
le agradezco nuevamente su ayuda.

por ultimo no pude acceder al link que me dejo para ver el ejemplo completo me dice que acceso denegado.


SJ Suyamburaja Jayakumar Syncfusion Team July 14, 2020 02:17 PM UTC

Hi Harrison Hincapie Cardona, 
 
Thanks for your update. 
 
From the provided update, we can confirm that your requirement is similar to that of provided solution #1. Based on the Y value range, we need to change each column segment color.  
  
Query: Data comes from a viewModel and I do not have a viewModel: 
  
Let us clear your doubts, even though data comes from web services, you have populated that data into List <SemeforoVO> listSemeforoVO and for that maintained class SemeforoVO  
  
Let’s compare the property usage similar that provided sample 
viewModel.Data 
listSemeforoVO 
XValue 
period   
YValue 
numerator 
 
Please ensure whether the data collection has ` numerator ` value with your mentioned limits (Is it also having data points range above 29).  
  
Please confirm whether is it applied only for a segment not for data marker or else both and if not applied both, please ensure that in SeriesRendered event 
  
Query: finally, I could not access the link that left me to see the full example tells me that access is denied. 
  
Sorry for the inconvenience caused, please find the below sample in below 
  
 
Regards, 
Suyamburaja J. 



HH Harrison Hincapie Cardona July 14, 2020 09:32 PM UTC

Señor Suyamburaja Jayakumar [Syncfusion]

Muchas gracias tiene toda la razón me ayudo mucho mas a despejar dudas con esta solución mas detallada, el error mio era que tenia ya definido un color para todas las barras y por eso no me dejaba ver el de la condicional, un error de principiante pero pues de esos errores se aprende.

mil gracias......

Cordialmente Harlinson Hincapie.... 


HH Harrison Hincapie Cardona July 14, 2020 10:57 PM UTC

Señor Suyamburaja Jayakumar [Syncfusion]

Que pena volver a preguntar, de casualidad esto mismo se podria con el If pero solo con el dataMarker,  es decir la misma solucion pero que me pinte segun el valor del eje solo el DataMarker y no la columna.

de antemano muchas gracias.

Cordialmente Harlinson Hincapie    


SJ Suyamburaja Jayakumar Syncfusion Team July 15, 2020 05:26 PM UTC

Hi Harrison Hincapie Cardona,  
  
Thanks for your update.  
     
Under your account, we have created a support incident to track the status of this reported query.     
     
Please log on to our support website to check for further updates.     
     
  
Regards,  
Suyamburaja J. 


Loader.
Up arrow icon