Search code examples
pandasnumpyplotlyscatterplotly-python

How can I change textposition on plotly based on the information?


I have this code:

data = go.Scatter(
          x=positionsX,
          y=positionsY,
          textposition='middle center',
          mode='markers+text',
          marker=dict(
            color=color,
            opacity=[1, 1, 1, 1, 1],
            size=[100, 70, 60, 30, 25]),
          text=list(sumByRegion.keys()),
        )

and I wanna change the textposition to 'bottom left' based on sumByRegion.keys() value.

sumByRegion.keys() is dict_values([55, 24, 16, 3, 2])

What I have now is on the image:

image

edit:

Actually, I was looking for set the textposition for each individual item. Therefore, I used a array of textposition to fix the problem.

data = go.Scatter(
          x=positionsX,
          y=positionsY,
          textposition=["middle center", "middle center", "middle center", "middle right", "middle left"],
          mode='markers+text',
          marker=dict(
            color=color,
            opacity=[1, 1, 1, 1, 1],
            size=[100, 70, 60, 30, 25]),
          text=list(sumByRegion.keys()),
        )

Solution

  • If the text you want to display is in dictionary format, then you can convert it to the format you want to display. I'm not sure what the desired format is, but I added a line break and added a percent sign.

    import plotly.graph_objects as go
    
    sumByRegion = {'USA':55,'EU':24,'Asia':16,'Africa':2,'South America':3}
    text = {'{}<br>{}%'.format(k,v) for k,v in zip(sumByRegion.keys(), sumByRegion.values())}
    
    data = go.Scatter(
              x=positionsX,
              y=positionsY,
              textposition='bottom left',
              mode='markers+text',
              marker=dict(
                color=color,
                opacity=[1, 1, 1, 1, 1],
                size=[100, 70, 60, 30, 25]),
              text=text,
            )