Mamed
Mamed

Reputation: 772

Skip first and last point connecting in matplotlib

I am trying to connect points of different colors in graph. But somehow it connect also first and last point I guess (when I am changing 'o' to 'o-'). I wen through several questions there, but did not find answer.

Initial plot:

Only points

What happened:

Lines

I was truing to connect first point to last to show the trajectory.

Code:

for k in range(0, n_clusters):
    x=[]
    y=[]
    for j in range(0, len(final_cluster_result[k])):
        x_res = list(final_cluster_result[k][j].longitude)
        y_res = list(final_cluster_result[k][j].latitude)
        x.append(x_res)
        y.append(y_res)
    x = [s for t in x for s in t]
    y = [s for t in y for s in t]
    plt.plot(x,y,'o',markersize=3)
    plt.grid(which='both')
    plt.title(f'Clustering {k}',fontsize=14)
    plt.xlabel("Longitude",fontsize=15)
    plt.ylabel("Latitude",fontsize=15)

Upvotes: 1

Views: 1330

Answers (1)

Neo
Neo

Reputation: 627

Unfortunately, I cannot help you with matplotlib but I can propose another plotting library. Having experience with similar spatial data (I see you have latitude-longitude) I have found plotly's mapbox to be easy for creating interactive maps, where trajectories can easily be plotted.

If you are interested, here is some sample code to get you started. I left several (not necessarily needed) layout properties from an older project. The code outputs an html file you can open to access your interactive map from your browser.

import pandas as pd
import plotly.graph_objects as go
import plotly.offline

df = #  dataframe with at least 'longitude','latitude','cluster' columns and 1 row for each point
your_color_list = # specify color for each cluster, using a colors list with length = n_clusters

# define the lines to be plotted
map_lines = []
for cluster, group in df.groupby('cluster'):  # group dataframe by cluster and iterate over the groups
    for i in range(len(group)): # iterate over each group (cluster) and plot the lines
        map_lines.append(
            go.Scattermapbox(
                lon=list(group['longitude']),
                lat=list(group['latitude']),
                mode='lines',
                line=go.scattermapbox.Line(
                    width=4,
                    color=your_color_list[i], 
                ),
            )
        )
# define the map's layout
map_layout = dict(
                autosize=True,
                showlegend=False,
                height=850,
                font=dict(color='#191A1A'),
                titlefont=dict(color='#191A1A', size=18),
                margin=dict(
                    l=25,
                    r=25,
                    b=25,
                    t=35
                ),
                hovermode='closest',
                plot_bgcolor='#fffcfc',
                paper_bgcolor='#fffcfc',
                legend=dict(font=dict(size=10), orientation='h'),
                title='Visualization of trajectories',
                mapbox=dict(
                    accesstoken = your_access_token, # get a free token from plotly site
                    style='outdoors',
                    center={'lon': 22,'lat': 40}, # define the coordinates of the center of your plot, now your map is over Greece
                    bearing=0,
                    zoom=14, # map zoom
                )
            )

fig = go.Figure(
    data=map_lines,
    layout=map_layout)

plotly.offline.plot(
    fig,
    filename='your_file_name_here.html')

Upvotes: 1

Related Questions