Matplotlib:如何从列表中为所有国家绘制随机颜色?
Matplotlib: how to plot a random colour to all countries from the list?
如何为列表中的每个国家分配随机颜色以在地图上绘制?
import matplotlib.pyplot as plt
import numpy as np
import geopandas as gpd
world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))
ax2 = world.plot(figsize=(15,15), edgecolor=u'white', color='gray')
countries = ['Germany', 'Norway', 'Russia', 'China', 'Japan']
world.loc[world['name'].isin(countries)].plot(edgecolor=u'white', color=np.random.rand(3,), ax=ax2)
ax2.axis('scaled')
plt.show()
现在看起来是这样的:
这似乎有效。有没有更好的方法?
for contry in countries:
world.loc[world['name'].isin([contry])].plot(edgecolor=u'white', color=np.random.rand(3,), ax=ax2)
ax2.axis('scaled')
我添加了这些行:
for name in (countries):
world.loc[world['name'].eq(name)].plot(edgecolor=u'white', color=np.random.rand(3,), ax=ax2)
而不是这一行:
world.loc[world['name'].isin(countries)].plot(edgecolor=u'white', color=np.random.rand(3,), ax=ax2)
完整代码:
import matplotlib.pyplot as plt
import numpy as np
import geopandas as gpd
world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))
ax2 = world.plot(figsize=(15,15), edgecolor=u'white', color='gray')
countries = ['Germany', 'Norway', 'Russia', 'China', 'Japan']
for name in (countries):
world.loc[world['name'].eq(name)].plot(edgecolor=u'white', color=np.random.rand(3,), ax=ax2)
ax2.axis('scaled')
plt.show()
输出:
如何为列表中的每个国家分配随机颜色以在地图上绘制?
import matplotlib.pyplot as plt
import numpy as np
import geopandas as gpd
world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))
ax2 = world.plot(figsize=(15,15), edgecolor=u'white', color='gray')
countries = ['Germany', 'Norway', 'Russia', 'China', 'Japan']
world.loc[world['name'].isin(countries)].plot(edgecolor=u'white', color=np.random.rand(3,), ax=ax2)
ax2.axis('scaled')
plt.show()
现在看起来是这样的:
这似乎有效。有没有更好的方法?
for contry in countries:
world.loc[world['name'].isin([contry])].plot(edgecolor=u'white', color=np.random.rand(3,), ax=ax2)
ax2.axis('scaled')
我添加了这些行:
for name in (countries):
world.loc[world['name'].eq(name)].plot(edgecolor=u'white', color=np.random.rand(3,), ax=ax2)
而不是这一行:
world.loc[world['name'].isin(countries)].plot(edgecolor=u'white', color=np.random.rand(3,), ax=ax2)
完整代码:
import matplotlib.pyplot as plt
import numpy as np
import geopandas as gpd
world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))
ax2 = world.plot(figsize=(15,15), edgecolor=u'white', color='gray')
countries = ['Germany', 'Norway', 'Russia', 'China', 'Japan']
for name in (countries):
world.loc[world['name'].eq(name)].plot(edgecolor=u'white', color=np.random.rand(3,), ax=ax2)
ax2.axis('scaled')
plt.show()
输出: