1

Using google colab (similar to Jupyter notebook) I'm trying to read in a cities.csv file that is in format: city,lat,long

I am able to plot the graph but I cannot seem to figure out how to get the [city] to be written above each plot point.

import matplotlib
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

col_names=['City','Lat','Long']
da = pd.read_csv('cities.csv',names=col_names,header=None,dtype=None)
print(da)

cityArray = da.City
x=da.Lat
y=da.Long

#df= pd.read_csv("cities.csv")
#df
#data = np.genfromtxt("cities.csv", delimiter=",", names=["city","x", "y"])
#print(data['city'])
#labels = [(data['city'])]
#print(labels)

plt.figure(figsize=(20,20))
plt.scatter(da.Long,da.Lat,s=20,color='red')
#for xz,yz in zip(x,y):
#  plt.text(x,y,'cityArray')
#plt.show();

cities.csv contents

Abilene,32.4543,-99.7384
Alice,27.7556,-98.0653
Amarillo,35.1989,-101.831
Austin,30.3006,-97.7517
Beaumont,30.085,-94.1451
Brownsville,25.998,-97.4565
College Station,30.5852,-96.296
Columbus,29.7055,-96.5563
Corpus Christi,27.7261,-97.3755
Dalhart,36.0579,-102.5123
Dallas,32.7936,-96.7662
Del Rio,29.3708,-100.88
El Paso,31.8479,-106.4309
Fort Worth,32.7812,-97.3472
Galveston,29.5112,-95.1979
Gonzalez,29.5126,-97.4472
Houston,29.7869,-95.3905
Jamaica Beach,29.1905,-94.9801
Kenedy,28.8176,-97.8518
Laredo,27.5617,-99.4874
Lubbock,33.5642,-101.8871
McAllen,26.2273,-98.2471
Midland,32.0249,-102.1137
New Braunfels,29.6997,-98.1148
Odessa,31.8831,-102.3406
Palestine,31.7544,-95.6471
Round Rock,30.5254,-97.6659
San Angelo,31.4426,-100.4501
San Antonio,29.4658,-98.5254
San Marcos,29.8736,-97.938
Seguin,29.5891,-97.9661
Sugar Land,29.5935,-95.6357
Temple,31.1076,-97.3894
Texarkana,33.4487,-94.0815
Three Rivers,28.4668,-98.1784
Uvalde,29.2153,-99.7782
Victoria,28.8285,-96.985
Waco,31.5597,-97.1882
Wichita Falls,33.9072,-98.529
StayHungry
  • 33
  • 1
  • 8
  • I tried this resource (https://queirozf.com/entries/add-labels-and-text-to-matplotlib-plots-annotation-examples) and several others but cannot get it to compile that way. – StayHungry Jun 20 '21 at 00:15
  • https://stackoverflow.com/a/46028674/6361531 – Scott Boston Jun 20 '21 at 00:20
  • @ScottBoston Checked that out, none of those apply towards a .csv data file input so it doesn't help :-\ – StayHungry Jun 20 '21 at 00:28
  • It should work the the same. I am using pandas to create a data frame from the text in your csv file. You should use pd.read_csv. – Scott Boston Jun 20 '21 at 00:35

1 Answers1

3

Try this:

col_names=['City','Lat','Long']
df = pd.read_clipboard(sep=',', names=col_names)

def label_point(x, y, val, ax):
    a = pd.concat({'x': x, 'y': y, 'val': val}, axis=1)
    for i, point in a.iterrows():
        ax.text(point['x']+.02, point['y'], str(point['val']))

ax = df.plot.scatter('Lat', 'Long', figsize=(12,8))
label_point(df['Lat'], df['Long'], df['City'], ax)

Output:

enter image description here

Scott Boston
  • 147,308
  • 15
  • 139
  • 187