Artur
Artur

Reputation: 41

Echarts Pie chart title center position

I have a default pie chart Pie Chart

with title inside like in documentation example:

option = {
  title: {
    text: 'A Case of Doughnut Chart',
    left: 'center',
    top: 'center'
  },
  series: [
    {
      type: 'pie',
      data: [
        {
          value: 335,
          name: 'A'
        },
        {
          value: 234,
          name: 'B'
        },
        {
          value: 1548,
          name: 'C'
        }
      ],
      radius: ['40%', '70%'],
      center: ['50%', '50%']
    }
  ]
};

It's centered perfectly until I change the center of pie chart - title still stays in one position while chart is in another position:

Pie Chart broken

Is it possible to connect title with pie chart or calculate the center position of the pie chart instead of using string value 'center'?

I can calculate the center of the container, but it doesn't match with the chart center

Upvotes: 0

Views: 30

Answers (1)

Artur
Artur

Reputation: 41

If someone facing this problem, I've found a simple solution:

  1. Set padding of title to 0. textAlign to center, textVerticalAlign to center
  2. Calculate top and left positions using chart size:
let chartWidth = chart.clientWidth;
let chartHeight = chart.clientHeight;

let offset // offset calculate like this: My chart center default position is [50%; 50%] so offset will be [0,0]. When I move chart to left I set center [60%, 50%] so offset will be [0.1, 0]. To right: [-0.1, 0]. To top: [0, 0.1],
To bottom: [0, -0.1]

let newTitlePositionLeft = chartWidth / 2 + (chartWidth * offset[0])
let newTitlePositionTop = chartHeight/ 2 + (chartHeight* offset[1])

  1. Update title position using setOption function

Upvotes: 0

Related Questions