c# - 以对数刻度显示刻度标签 MS 图表 (log-log)

标签 c# charts .net-4.5 mschart

我在 Visual Studio 2015 (C#) 中使用 MS Charts 创建了一个图,具有对数刻度(两个轴)(见图)。

我需要在 x 轴上添加更多的网格线和相应的标签。我想标记 1 (2, 3, 4...) 和 10 之间以及 10 和 100 (20, 30, 40...) 之间的每个小刻度线,而且,我想在例如之间添加网格线。 10 和 20。

我使用 1 的间隔作为图表轴属性中的标签,但它不起作用。

Chart with log scale

最佳答案

在(!)在非零 x 值处添加一个点设置chart.SuppressExceptions = true后,您可以将这些属性用于Chararea ca:

ca.AxisX.IsLogarithmic = true;
ca.AxisX.LogarithmBase = 10;

// with 10 as the base it will go to 1, 10, 100, 1000..
ca.AxisX.Interval = 1;

// this adds 4 tickmarks into each interval:
ca.AxisX.MajorTickMark.Interval = 0.25;

// this add 8 gridlines into each interval:
ca.AxisX.MajorGrid.Interval = 0.125;

// this sets two i.e. adds one extra label per interval
ca.AxisX.LabelStyle.Interval = 0.5;
ca.AxisX.LabelStyle.Format = "#0.0";

enter image description here

更新:

由于您不想使用自动标签(始终按值对齐),因此您需要添加 CustomLabels

为此,您需要设置要显示标签的位置/值列表:

    // pick a better name!
    List<double> xs = new List<double>() { 1, 2, 3, 4, 5, 10, 20, 50, 100, 200, 500, 1000};

接下来我们需要为我们创建的每个 CustomLabel 分配一个 FromPosition 和一个 ToPosition。这总是有点棘手,但这里比平时更棘手..

这两个值需要间隔足够远以允许标签适合..所以我们选择一个间隔因子:

    double spacer = 0.9d;

并且我们还关闭了自动适配机制:

    ca.AxisX.IsLabelAutoFit = false;

现在我们可以添加CustomLabels:

    for (int i = 0; i < xs.Count; i++)
    {
        CustomLabel cl = new CustomLabel();
        if (xs[i] == 1 || xs[i] <= 0)
        {
            cl.FromPosition = 0f;
            cl.ToPosition = 0.01f;
        }
        else
        {
            cl.FromPosition = Math.Log10(xs[i] * spacer);
            cl.ToPosition = Math.Log10(xs[i] / spacer);
        }

        cl.Text = xs[i] + "";
        ca.AxisX.CustomLabels.Add(cl);

    }

如您所见,我们需要使用应用于 AxisLog10 函数来计算值,间距是通过乘/除间隔符实现的,而不是通过增加。间距值也必须按 Log10 缩放并包含在函数中。

我们还需要处理 1 值的情况,这相当于 0 的标签位置;但这不会在乘法/除法时产生任何间距。所以我们手动设置一个合适的ToPosition

我希望我知道一个更简单的方法来做到这一点,但由于标签位置列表实际上是您的选择,我怀疑是否有捷径..

enter image description here

我在 40 和 50 处添加了点以显示一个标签是如何匹配的。还要注意标签位置是如何混合的。请随意使用您的!

关于c# - 以对数刻度显示刻度标签 MS 图表 (log-log),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37244461/

相关文章:

c# - 如何在 openSUSE 上安装 libgdiplus?

PHP-如何从数据库中按最高到最低顺序获取前十条记录

javascript - 图表的外部样式

sdk - Visual Studio 2012 命令行构建

c# - 当计算机从 sleep /休眠模式恢复时如何捕获事件?

c# - Async-Await 表达式返回错误结果

c# - 从 C# 读取和写入 Microsoft Project 2007

c# - DataTable 不显示分钟和秒

c# - 阻止拆分器在 C# 中缩放面板?

c# - 将 List<double> 转换为 LiveCharts.IChartValues