From b491d6b4dc5c768fa5f24d9e83f5485e0395a6ce Mon Sep 17 00:00:00 2001 From: Leon Sorokin Date: Tue, 1 Mar 2022 01:55:53 -0600 Subject: [PATCH] Histogram: auto-skip x tick labels to avoid overlap (#45996) --- .../app/plugins/panel/histogram/Histogram.tsx | 25 +++++++++++++++++-- 1 file changed, 23 insertions(+), 2 deletions(-) diff --git a/public/app/plugins/panel/histogram/Histogram.tsx b/public/app/plugins/panel/histogram/Histogram.tsx index a4b21980c2f..29115ecff96 100644 --- a/public/app/plugins/panel/histogram/Histogram.tsx +++ b/public/app/plugins/panel/histogram/Histogram.tsx @@ -15,7 +15,15 @@ import { getFieldSeriesColor, GrafanaTheme2, } from '@grafana/data'; -import { Themeable2, UPlotConfigBuilder, UPlotChart, VizLayout, PlotLegend } from '@grafana/ui'; +import { + Themeable2, + UPlotConfigBuilder, + UPlotChart, + VizLayout, + PlotLegend, + measureText, + UPLOT_AXIS_FONT_SIZE, +} from '@grafana/ui'; import { histogramBucketSizes, @@ -119,7 +127,20 @@ const prepConfig = (frame: DataFrame, theme: GrafanaTheme2) => { placement: AxisPlacement.Bottom, incrs: histogramBucketSizes, splits: xSplits, - values: (u: uPlot, vals: any[]) => vals.map(xAxisFormatter), + values: (u: uPlot, splits: any[]) => { + const tickLabels = splits.map(xAxisFormatter); + + const maxWidth = tickLabels.reduce( + (curMax, label) => Math.max(measureText(label, UPLOT_AXIS_FONT_SIZE).width, curMax), + 0 + ); + + const labelSpacing = 10; + const maxCount = u.bbox.width / ((maxWidth + labelSpacing) * devicePixelRatio); + const keepMod = Math.ceil(tickLabels.length / maxCount); + + return tickLabels.map((label, i) => (i % keepMod === 0 ? label : null)); + }, //incrs: () => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10].map((mult) => mult * bucketSize), //splits: config.xSplits, //values: config.xValues,