Forum Discussion

JohanSmith7's avatar
JohanSmith7
Frequent Visitor
3 years ago
Solved

How to format dynamic X axis in a Bar Chart

Hi all, I have a table with demand values in different dates and need a bar chart that changes the labels in x axis based on the date selected in a filter. I have attached Sample data.    Let's say...
  • v-jianboli-msft's avatar
    3 years ago

    Hi JohanSmith7 ,

     

    Please try:

    First create a new table for x-axis:

    X-axis = 
    var _a = DISTINCT(SELECTCOLUMNS('Table',"YearMonth",FORMAT([Date],"MMM-YY"),"Rank",RANKX('Table',YEAR([Date])*100+MONTH([Date]),,ASC,Dense)))
    var _b = COUNTROWS(_a)
    return UNION(_a,{("> 6 months",_b),("< 6 months",0)})

    Then apply this measure to the chart:

    Measure =
    VAR _a =
        MIN ( 'Table'[Date] )
    VAR _b =
        SELECTCOLUMNS (
            CALENDAR ( _a, EDATE ( _a, 5 ) ),
            "YearMonth", FORMAT ( [Date], "MMM-YY" )
        ) //6 months
    VAR _c =
        CALCULATE (
            SUM ( 'Table'[Demand] ),
            FILTER (
                ALL ( 'Table' ),
                FORMAT ( [Date], "MMM-YY" ) = SELECTEDVALUE ( 'X-axis'[YearMonth] )
            )
        ) // calculate value for selected month
    VAR _d =
        CALCULATE ( SUM ( 'Table'[Demand] ), FILTER ( ALL ( 'Table' ), [Date] < _a ) ) //calculate value for < 6months
    VAR _e =
        CALCULATE (
            SUM ( 'Table'[Demand] ),
            FILTER ( ALL ( 'Table' ), [Date] > EOMONTH ( _a, 5 ) )
        ) //calculate value for > 6months
    RETURN
        SWITCH (
            TRUE (),
            SELECTEDVALUE ( 'X-axis'[YearMonth] ) IN _b,
                CALCULATE (
                    SUM ( 'Table'[Demand] ),
                    FILTER (
                        ALL ( 'Table' ),
                        FORMAT ( [Date], "MMM-YY" ) = SELECTEDVALUE ( 'X-axis'[YearMonth] )
                    )
                ),
            SELECTEDVALUE ( 'X-axis'[YearMonth] ) = "< 6 months", _d,
            SELECTEDVALUE ( 'X-axis'[YearMonth] ) = "> 6 months", _e
        )
    

    Final output:

    Best Regards,

    Jianbo Li

    If this post helps, then please consider Accept it as the solution to help the other members find it more quickly.