Home > Software design >  How to plot a graph over map of a country?
How to plot a graph over map of a country?

Time:07-16

The code I tried is,

df = pd.DataFrame({'x':phi_pp, 'y':lambda_pp})
df.plot('x', 'y', kind='line',legend=None)
plt.xlabel('IPP Longitude')
ax=plt.ylabel('IPP Latitude')

im = plt.imread("Map_of_India.jpg")
fig, ax = plt.subplots()
plt.show()

The sample df is:

         x          y
0   15.121270   4246.948356
1   12.103705   4248.927074
2   8.583936    4247.596317
3   18.173364   4244.749973
4   14.175727   4290.142397

The two plots are not plotting on same axes. Any image of Indian map can be used as a sample image.

CodePudding user response:

You can first plot the image using imshow. Then make a second axes at the same position as the image axes and set its background transparent. Now you can plot your dataframe on this new axes and it will overlay the image.

import pandas as pd
import matplotlib.pyplot as plt

im = plt.imread('https://static01.nyt.com/newsgraphics/2021/coronavirus-tracking/images/maps/IND/hotspots.png')

df = pd.DataFrame({'x': [15.12127, 12.103705, 8.583936, 18.173364, 14.175727],
                   'y': [4246.948356, 4248.927074, 4247.596317, 4244.749973, 4290.142397]})

fig, ax_im = plt.subplots()
ax_im.imshow(im)
ax_im.set_axis_off()

ax_df = fig.add_axes(ax_im.get_position())
ax_df.patch.set_alpha(0)
df.plot('x', 'y', legend=None, xlabel='IPP Longitude', ylabel='IPP Latitude', ax=ax_df)

enter image description here

  • Related