Search code examples
chartsxamarin.formsoxyplot

How to possible Xamarin Forms Vertical Bar Charts?


In my xamarin forms application, I am using the Oxyplot bar charts. Here is the code, This is work for me in the condition for horizontal bars, How it is possible for creating for vertical graphs? Is there any other plugin for bar charts?


Solution

  • The key is to use a ColumnSeries with ColumnItem objects. This should render as a bar chart that has vertically oriented bars. If you create a new ContentPage and paste the code below into it you can see it in action. I attached an image below the code sample detailing how it looks on iOS.

    public partial class DemoPage : ContentPage
    {
        public DemoPage()
        {
            InitializeComponent();
    
            var model = new PlotModel { Title = "Cake Type Popularity" };
    
            // generate a random percentage distribution between the 5
            //cake-types (see axis below)
            var rand = new Random();
            double[] cakePopularity = new double[5];
            for (int i = 0; i < 5; ++i)
            {
                cakePopularity[i] = rand.NextDouble();
            }
            var sum = cakePopularity.Sum();
    
            var barSeries = new ColumnSeries
            {
    
                ItemsSource = new List<ColumnItem>(new[]
                {
                    new ColumnItem{ Value = (cakePopularity[0] / sum * 100) },
                    new ColumnItem{ Value = (cakePopularity[1] / sum * 100) },
                    new ColumnItem{ Value = (cakePopularity[2] / sum * 100) },
                    new ColumnItem{ Value = (cakePopularity[3] / sum * 100) },
                    new ColumnItem{ Value = (cakePopularity[4] / sum * 100) }
                }),
                LabelPlacement = LabelPlacement.Inside,
                LabelFormatString = "{0:.00}%"
            };
    
            model.Series.Add(barSeries);
    
            model.Axes.Add(new CategoryAxis
            {
                Position = AxisPosition.Bottom,
    
                Key = "CakeAxis",
                ItemsSource = new[]
                {
                    "A",
                    "B",
                    "C",
                    "D",
                    "E"
                }
            });
    
            var grid = new Grid();
    
            grid.Children.Add(new PlotView
            {
                Model = model,
                VerticalOptions = LayoutOptions.Center,
                HeightRequest = 200,
                HorizontalOptions = LayoutOptions.Fill,
            });
    
            Content = grid;
        }
    }
    

    This should render a graph like this:

    Graph with ColumnSeries