Search code examples
pythonhvplot

How to change position of labels on top of plots by using hvPlot


By using hvplot.labels() with text_align='left', I could change the label position to right like this:

import hvplot.pandas 
import pandas as pd
df = pd.DataFrame(
    {'City': ['Buenos Aires', 'Brasilia', 'Santiago', 'Bogota', 'Caracas'],
     'Country': ['Argentina', 'Brazil', 'Chile', 'Colombia', 'Venezuela'],
     'Latitude': [-34.58, -15.78, -33.45, 4.60, 10.48],
     'Longitude': [-58.66, -47.91, -70.66, -74.08, -66.86]})
df.hvplot.points(x='Longitude', y='Latitude', padding=0.2, hover_cols='all', width=300) * \
df.hvplot.labels(x='Longitude', y='Latitude', text='City', 
text_align='left', hover=False).opts(text_font_size='7pt')

enter image description here

But the labels still overlap with the round marks, so I want to shift them more to the right. How can I get the following diagram? For now, the only way I can think of is to add a space at the beginning of the label...

enter image description here


Solution

  • In the last line, within opts(), you can add xoffset=0.7 and that should move the labels to the right. Updated code and plot below.

    import hvplot.pandas 
    import pandas as pd
    df = pd.DataFrame(
        {'City': ['Buenos Aires', 'Brasilia', 'Santiago', 'Bogota', 'Caracas'],
         'Country': ['Argentina', 'Brazil', 'Chile', 'Colombia', 'Venezuela'],
         'Latitude': [-34.58, -15.78, -33.45, 4.60, 10.48],
         'Longitude': [-58.66, -47.91, -70.66, -74.08, -66.86]})
    df.hvplot.points(x='Longitude', y='Latitude', padding=0.2, hover_cols='all', width=300) * \
    df.hvplot.labels(x='Longitude', y='Latitude', text='City', 
    text_align='left', hover=False).opts(xoffset=0.7, text_font_size='7pt')
    

    Output plot

    enter image description here