mapplot.py-20171101

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 19 16:15:01 2017

@author: vicky
"""

import numpy as np
# import matplotlib.pyplot as plt
#
# plt.axis([0, 100, 0, 1])
# plt.ion()
#
# for i in range(100):
#     y = np.random.random()
#     plt.scatter(i, y)
#     plt.pause(0.1)

from matplotlib.patches import Circle
import matplotlib.pyplot as plt
import xlrd
from matplotlib.animation import FuncAnimation
import matplotlib.ticker as mticker
import cartopy.crs as ccrs
from cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER

fig = plt.figure()
ax = plt.axes(projection=ccrs.Mercator())
ax.coastlines()
gl = ax.gridlines(crs=ccrs.PlateCarree(), draw_labels=True,
           linewidth=2, color='gray', alpha=15, linestyle='--')
gl.xlabels_top = False
gl.ylabels_left = False
gl.xlines = False
gl.xlocator = mticker.FixedLocator([-180, -45, 0, 45, 180])
gl.xformatter = LONGITUDE_FORMATTER
gl.yformatter = LATITUDE_FORMATTER
gl.xlabel_style = {'size': 15, 'color': 'gray'}
gl.xlabel_style = {'color': 'red', 'weight': 'bold'}

lats = []
lons = []
data = xlrd.open_workbook("/Users/vicky/Documents/电力/1019/points2.xlsx")
#data=[-121,343]
table = data.sheets()[0]
#table=[35,45]
ncols = table.ncols
nrows = table.nrows
for i in range(nrows):
    cir1 = Circle(xy=(float(table.col(0)[i].value), float(table.col(1)[i].value)), radius=2, alpha=0.5)
#,transform=ccrs.PlateCarree())
    lons.append(cir1)
    ax.add_artist(lons[i])  # 填充多边形内部


def update(framedata):
    global lons
    for i in range(nrows):
        lons[i].radius += 1
        if lons[i].radius == 15:
            lons[i].radius = 2
    return lons


animation = FuncAnimation(fig, update, interval=50)
plt.show()





from matplotlib.patches import Circle
import matplotlib.pyplot as plt
import xlrd
from matplotlib.animation import FuncAnimation
fig=plt.figure()#一个窗口
ax=fig.add_subplot(111)#一个表,一行一列第一块
#============================================# read data
lats  = []
lons  = []
data=xlrd.open_workbook("/Users/vicky/Documents/电力/1019/points2.xlsx")
table=data.sheets()[0]
ncols=table.ncols
nrows=table.nrows

for i in range(nrows):
    cir1=Circle(xy=(float(table.col(0)[i].value),float(table.col(1)[i].value)),radius=0.01,alpha=0.5)#线粗
    p2=plt.plot(float(table.col(0)[i].value),float(table.col(1)[i].value),'o',color='k',markersize=t)
    lons.append(p2)
    lons.append(cir1)
    #ax.add_patch(lons[i])#填充多边形内部
def update(framedata):
    global lons
    for i in range(nrows):
     lons[i].radius+=0.01
     if lons[i].radius==0.05:
        lons[i].radius=0.01
    return lons
#plt.axis('equal')
animation = FuncAnimation(fig, update, interval=100)
plt.show()






from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt

map = Basemap(llcrnrlon=-0.5,llcrnrlat=39.8,urcrnrlon=4.,urcrnrlat=43.,
             resolution='i', projection='tmerc', lat_0 = 39.5, lon_0 = 1)

map.drawmapboundary(fill_color='aqua')
map.fillcontinents(color='#ddaa66',lake_color='aqua')
map.drawcoastlines()

map.readshapefile('../sample_files/comarques', 'comarques')

lightning_info = map.readshapefile('../sample_files/lightnings', 'lightnings')

print lightning_info

for info, lightning in zip(map.lightnings_info, map.lightnings):
    if float(info['amplitude']) < 0:
        marker = '_'
    else:
        marker = '+'
    map.plot(lightning[0], lightning[1], marker=marker, color='m', markersize=8, markeredgewidth=2)

plt.show()










from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1.inset_locator import zoomed_inset_axes
from mpl_toolkits.axes_grid1.inset_locator import mark_inset
import numpy as np
fig = plt.figure()
ax = fig.add_subplot(111)

map = Basemap(projection='cyl', 
              lat_0=0, lon_0=0)

map.drawmapboundary(fill_color='#7777ff')
map.fillcontinents(color='#ddaa66', lake_color='#7777ff', zorder=0)
map.drawcoastlines()

lons = np.array([-13.7, -10.8, -13.2, -96.8, -7.99, 7.5, -17.3, -3.7])
lats = np.array([9.6, 6.3, 8.5, 32.7, 12.5, 8.9, 14.7, 40.39])
cases = np.array([1971, 7069, 6073, 4, 6, 20, 1, 1])
deaths = np.array([1192, 2964, 1250, 1, 5, 8, 0, 0])
places = np.array(['Guinea', 'Liberia', 'Sierra Leone','United States', 'Mali', 'Nigeria', 'Senegal', 'Spain'])

x, y = map(lons, lats)

map.scatter(x[1], y[1], s=100, c='b', alpha=0.5)

axins = zoomed_inset_axes(ax, 7, loc=1)
axins.set_xlim(-20, 0)
axins.set_ylim(3, 18)

plt.xticks(visible=False)
plt.yticks(visible=False)

map2 = Basemap(llcrnrlon=-20,llcrnrlat=3,urcrnrlon=0,urcrnrlat=18, ax=axins)
map2.drawmapboundary(fill_color='#7777ff')
map2.fillcontinents(color='#ddaa66', lake_color='#7777ff', zorder=0)
map2.drawcoastlines()
map2.drawcountries()

map2.scatter(x, y, s=cases/5., c='r', alpha=0.5)

mark_inset(ax, axins, loc1=2, loc2=4, fc="none", ec="0.5")

plt.show()











# import matplotlib.pyplot as plt
# from matplotlib.patches import Circle
# import numpy as np
# import math
#
# plt.close()  # clf() # 清图  cla() # 清坐标轴 close() # 关窗口
# fig = plt.figure()
# ax = fig.add_subplot(1, 1, 1)
# ax.axis("equal")  # 设置图像显示的时候XY轴比例
# plt.grid(True)  # 添加网格
# plt.ion()  # interactive mode on
# IniObsX = 0000
# IniObsY = 4000
# IniObsAngle = 135
# IniObsSpeed = 10 * math.sqrt(2)  # 米/秒
# print('开始仿真')
# try:
#     for t in range(180):
#         # 障碍物船只轨迹
#         obsX = IniObsX + IniObsSpeed * math.sin(IniObsAngle / 180 * math.pi) * t
#         obsY = IniObsY + IniObsSpeed * math.cos(IniObsAngle / 180 * math.pi) * t
#         ax.scatter(obsX, obsY, c='b', marker='.')  # 散点图
#         # ax.lines.pop(1)  删除轨迹
#         # 下面的图,两船的距离
#         plt.pause(0.001)
# except Exception as err:
#     print(err)

import matplotlib.pyplot as plt
import cartopy.crs as crs
from matplotlib.offsetbox import AnnotationBbox, OffsetImage
from PIL import Image
 
lat = 117
lon = 39
img = Image.open('/Users/vicky/Documents/code/python/tjmap.png')
 
fig = plt.figure(figsize=(10, 5))
ax = plt.axes(projection=crs.PlateCarree())
ax.coastlines()
ax.stock_img()
imagebox = OffsetImage(img, zoom=0.1)
imagebox.image.axes = ax
ab = AnnotationBbox(imagebox, [lat, lon], pad=0, frameon=False)
ax.add_artist(ab)
 
plt.show()


import matplotlib.patches as mpatches
import matplotlib.pyplot as plt
import shapely.geometry as sgeom
import cartopy.crs as ccrs
import cartopy.io.shapereader as shpreader


def sample_data():
    """
    Returns a list of latitudes and a list of longitudes (lons, lats)
    for Hurricane Katrina (2005).

    The data was originally sourced from the HURDAT2 dataset from AOML/NOAA:
    http://www.aoml.noaa.gov/hrd/hurdat/newhurdat-all.html on 14th Dec 2012.

    """
    lons = [-75.1, -75.7, -76.2, -76.5, -76.9, -77.7, -78.4, -79.0,
            -79.6, -80.1, -80.3, -81.3, -82.0, -82.6, -83.3, -84.0,
            -84.7, -85.3, -85.9, -86.7, -87.7, -88.6, -89.2, -89.6,
            -89.6, -89.6, -89.6, -89.6, -89.1, -88.6, -88.0, -87.0,
            -85.3, -82.9]

    lats = [23.1, 23.4, 23.8, 24.5, 25.4, 26.0, 26.1, 26.2, 26.2, 26.0,
            25.9, 25.4, 25.1, 24.9, 24.6, 24.4, 24.4, 24.5, 24.8, 25.2,
            25.7, 26.3, 27.2, 28.2, 29.3, 29.5, 30.2, 31.1, 32.6, 34.1,
            35.6, 37.0, 38.6, 40.1]

    return lons, lats


def main():
    ax = plt.axes([0, 0, 1, 1],
                  projection=ccrs.LambertConformal())

    ax.set_extent([-125, -66.5, 20, 50], ccrs.Geodetic())

    shapename = 'admin_1_states_provinces_lakes_shp'
    states_shp = shpreader.natural_earth(resolution='110m',
                                         category='cultural', name=shapename)

    lons = [-75.1, -75.7, -76.2, -76.5, -76.9, -77.7, -78.4, -79.0,
            -79.6, -80.1, -80.3, -81.3, -82.0, -82.6, -83.3, -84.0,
            -84.7, -85.3, -85.9, -86.7, -87.7, -88.6, -89.2, -89.6,
            -89.6, -89.6, -89.6, -89.6, -89.1, -88.6, -88.0, -87.0,
            -85.3]

    lats = [23.1, 23.4, 23.8, 24.5, 25.4, 26.0, 26.1, 26.2, 26.2, 26.0,
            25.9, 25.4, 25.1, 24.9, 24.6, 24.4, 24.4, 24.5, 24.8, 25.2,
            25.7, 26.3, 27.2, 28.2, 29.3, 29.5, 30.2, 31.1, 32.6, 34.1,
            35.6, 37.0, 38.6]

    # to get the effect of having just the states without a map "background"
    # turn off the outline and background patches
    ax.background_patch.set_visible(False)
    ax.outline_patch.set_visible(False)

    plt.title('US States which intersect the track '
              'of Hurricane Katrina (2005)')

    # turn the lons and lats into a shapely LineString
    track = sgeom.LineString(zip(lons, lats))

    # buffer the linestring by two degrees (note: this is a non-physical
    # distance)
    track_buffer = track.buffer(2)

    for state in shpreader.Reader(states_shp).geometries():
        # pick a default color for the land with a black outline,
        # this will change if the storm intersects with our track
        facecolor = [0.9375, 0.9375, 0.859375]
        edgecolor = 'black'

        if state.intersects(track):
            facecolor = 'red'
        elif state.intersects(track_buffer):
            facecolor = '#FF7E00'

        ax.add_geometries([state], ccrs.PlateCarree(),
                          facecolor=facecolor, edgecolor=edgecolor)

    ax.add_geometries([track_buffer], ccrs.PlateCarree(),
                      facecolor='#C8A2C8', alpha=0.5)
    ax.add_geometries([track], ccrs.PlateCarree(),
                      facecolor='none')

    # make two proxy artists to add to a legend
    direct_hit = mpatches.Rectangle((0, 0), 1, 1, facecolor="red")
    within_2_deg = mpatches.Rectangle((0, 0), 1, 1, facecolor="#FF7E00")
    labels = ['State directly intersects\nwith track',
              'State is within \n2 degrees of track']
    plt.legend([direct_hit, within_2_deg], labels,
               loc='lower left', bbox_to_anchor=(0.025, -0.1), fancybox=True)

    plt.show()


if __name__ == '__main__':
    main()

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap 
from matplotlib.patches import Polygon

fig = plt.figure()
ax1 = fig.add_axes([0.1,0.1,0.8,0.8])
bmap = Basemap(llcrnrlon=116,llcrnrlat=38.5,urcrnrlon=119,urcrnrlat=40.3,
            projection='lcc',lat_1=38,lat_2=39,lon_0=116, ax=ax1)
shp_info = bmap.readshapefile('/Users/vicky/Documents/code/python/CHN_adm_shp/CHN_adm3','states',drawbounds=False)

for info, shp in zip(bmap.states_info, bmap.states):
    proid = info['NAME_1']
    if proid == 'Tianjin':
        poly = Polygon(shp,facecolor='w',edgecolor='b', lw=0.2)
        ax1.add_patch(poly)
    
bmap.drawcoastlines()
bmap.drawcountries()
bmap.drawparallels(np.arange(23,29,2),labels=[1,0,0,0])
bmap.drawmeridians(np.arange(115,121,2),labels=[0,0,0,1])
plt.title('Fujian Province')
plt.show()
#plt.savefig('fig_province.png', dpi=100, bbox_inches='tight')
#plt.clf()
#plt.close()

from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
from matplotlib.patches import Polygon
fig = plt.figure()
ax1 = fig.add_axes([0.1,0.1,0.8,0.8])

map = Basemap(llcrnrlon=116,llcrnrlat=38.5,urcrnrlon=119,urcrnrlat=40.3,
             resolution='i', projection='cass', lat_0 = 39,lon_0=117.5,ax=ax1)

shp_info = map.readshapefile("/Users/vicky/Documents/code/python/CHN_adm_shp/CHN_adm3",'states',drawbounds=True) # CHN_adm1的数据是中国各省区域

for info, shp in zip(map.states_info, map.states):
    proid = info['NAME_1']  # 可以用notepad打开CHN_adm1.csv文件,可以知道'NAME_1'代表各省的名称
    if proid == 'Tianjin':
        poly = Polygon(shp,facecolor='w',edgecolor='b', lw=3) # 绘制广东省区域
        ax1.add_patch(poly)

#map.shadedrelief() # 绘制阴暗的浮雕图
#map.drawcoastlines()#海岸线

lons=[117.0412,117.0717,117.0715,117.2928,117.1049,117.0412,117.1049,
        117.1475,117.1475,117.1475,117.1475,117.0342,117.0904,116.9811,
        117.1467,117.0344,117.1467,117.4576,117.2358,117.4576,117.6733,
        117.6692,117.6692,117.4576]
lats=[39.459,39.2281,39.2281,39.2785,38.9944,39.459,38.9944,39.1021,
      39.1021,39.1021,39.1021,38.9171,38.828,38.9683,38.6949,38.9171,
      38.6949,38.9615,39.0735,38.9615,39.0642,39.0446,39.0446,38.9615]

x, y = map(lons, lats)
map.scatter(x, y, marker='o')
#map.tissot(x, y, 4, 50)

map.shadedrelief() # 绘制阴暗的浮雕图
map.drawcoastlines()#海岸线

lon = 117.0412
lat = 39.459
x, y = map(lon, lat)
plt.text(x, y, 'Lagos',fontsize=12,fontweight='bold',ha='left',va='bottom',color='k')

plt.show()
#plt.close()

from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
# setup Lambert Conformal basemap.
# set resolution=None to skip processing of boundary datasets.
m = Basemap(width=12000000,height=9000000,projection='lcc',
            resolution=None,lat_1=45.,lat_2=55,lat_0=50,lon_0=-107.)
m.shadedrelief()
plt.show()


from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
import numpy as np

fig=plt.figure(figsize=(9, 3))

map = Basemap(width=12000000,height=8000000,
            resolution='l',projection='stere',
            lat_ts=50,lat_0=50,lon_0=-107.)

lons, lats, x, y = map.makegrid(30, 30, returnxy=True)

ax = fig.add_subplot(121)
ax.set_title('The regular grid')
map.scatter(x, y, marker='o')
map.drawcoastlines()


ax = fig.add_subplot(122)
ax.set_title('Projection changed')

map = Basemap(width=12000000,height=9000000,projection='aeqd',
            lat_0=50.,lon_0=-105.)
x, y = map(lons, lats)
map.scatter(x, y, marker='o')
map.drawcoastlines()

plt.show()




import time

start = time.clock()
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
from matplotlib.patches import Polygon
import pandas as pd
import numpy as np
posi=pd.read_excel("D:\\Files\\datasets\\2015Cities-CHINA.xlsx") #读取中国城市数据
lat = np.array(posi["lat"][0:120])                        # 获取维度之维度值
lon = np.array(posi["lon"][0:120])                        # 获取经度值
pop = np.array(posi["pop"][0:120],dtype=float) 
size=(pop/np.max(pop))*100  


map = Basemap(llcrnrlon=80.33, 
              llcrnrlat=3.01, 
              urcrnrlon=138.16, 
              urcrnrlat=56.123,
             resolution='h', projection='cass', lat_0 = 42.5,lon_0=120)

map.readshapefile("/Users/vicky/Documents/code/python/CHN_adm_shp/CHN_adm1",'states',drawbounds=True)

map.etopo() # 绘制地形图,浮雕样式

map.drawcoastlines()

x,y = map(90,40) # 北京市坐标,经纬度坐标转换为该map的坐标

a,b = map(lon,lat)

# map.scatter(a,b,s=size) # 取消注释此行即可获得中国各地区人口分布示意图

map.scatter(x,y,s=200,marker='*',facecolors='r',edgecolors='r') # 绘制首都

end=time.clock()

print(end-start)

plt.show()




from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
import numpy as np


plt.figure(1)
map = Basemap(projection='merc',
              resolution='l',
              llcrnrlat=44.0,
              llcrnrlon=5.0,
              urcrnrlat=57.0,
              urcrnrlon=17)
map.drawcoastlines()
map.drawcountries()
map.fillcontinents(color='lightgray')
map.drawmapboundary()

long = np.array([ 13.404954,  11.581981,   9.993682,   8.682127,   6.960279,
         6.773456,   9.182932,  12.373075,  13.737262,  11.07675 ,
         7.465298,   7.011555,  12.099147,   9.73201 ,   7.628279,
         8.801694,  10.52677 ,   8.466039,   8.239761,  10.89779 ,
         8.403653,   8.532471,   7.098207,   7.216236,   9.987608,
         7.626135,  11.627624,   6.852038,  10.686559,   8.047179,
         8.247253,   6.083887,   7.588996,   9.953355,  10.122765])

lat = np.array([ 52.520007,  48.135125,  53.551085,  50.110922,  50.937531,
        51.227741,  48.775846,  51.339695,  51.050409,  49.45203 ,
        51.513587,  51.455643,  54.092441,  52.375892,  51.36591 ,
        53.079296,  52.268874,  49.487459,  50.078218,  48.370545,
        49.00689 ,  52.030228,  50.73743 ,  51.481845,  48.401082,
        51.960665,  52.120533,  51.47512 ,  53.865467,  52.279911,
        49.992862,  50.775346,  50.356943,  49.791304,  54.323293])

colors = np.array([ 2.72189792,  3.62138986,  1.7947676 ,  1.36524602,  1.75664228,
        3.0777491 ,  2.39580451,  1.17822874,  1.35503558,  2.28517658,
        3.66472978,  1.76467741,  0.72551119,  1.76997962,  4.49420944,
        2.34434288,  1.3243405 ,  2.35945794,  3.16147488,  2.94025564,
        1.68774158,  0.67602518,  1.60727613,  1.85608281,  3.57769226,
        1.33501838,  3.32549868,  2.95492675,  2.83391381,  2.33983198,
        2.59607424,  1.24260218,  1.89258818,  2.07508363,  3.03319927])

x, y = map(long, lat)
map.plot(x,y,'o')
plt.show()








from matplotlib import pyplot as plt
import matplotlib.animation as animation
import numpy as np
 
 
def update_point(num):
    fig_points.set_data(data[:, 0:num])
    return fig_points,
 
fig1 = plt.figure()
 
num_point = 50
data = np.random.rand(2, num_point)
fig_points, = plt.plot([], [], 'ro')
 
plt.xlim(0, 1)
plt.ylim(0, 1)
plt.xlabel('x')
plt.title('Scatter Point')
 
# interval
# repeat
# frames
# fargs
# init_func
anim = animation.FuncAnimation(fig1, update_point,num_point)
 
#anim = animation.FuncAnimation(fig1, update_point,frames=num_point, interval=50, blit=False, repeat=False)
 
plt.show()





import sys
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

fig, ax = plt.subplots()
fig.set_tight_layout(True)

#  询问图形在屏幕上的尺寸和DPI(每英寸点数)。
#  注意当我们把图形储存成一个文件时,我们需要再另外提供一个DPI值
#print('fig size: {0} DPI, size in inches {1}'.format(
#    fig.get_dpi(), fig.get_size_inches()))

# 画出一个维持不变(不会被重画)的散点图和一开始的那条直线。
x = np.arange(0, 20, 0.1)
ax.scatter(x, x + np.random.normal(0, 3.0, len(x)))
p, = ax.plot(x, x - 5, 'r-', linewidth=2)

def update(i):
    label = 'timestep {0}'.format(i)
    print(label)
    # 更新直线和x轴(用一个新的x轴的标签)。
    # 用元组(Tuple)的形式返回在这一帧要被重新绘图的物体
    p.set_ydata(x - 5 + i)
    ax.set_xlabel(label)
    return p, ax

if __name__ == '__main__':
    # FuncAnimation 会在每一帧都调用“update” 函数。
    # 在这里设置一个10帧的动画,每帧之间间隔200毫秒
    anim = FuncAnimation(fig, update, frames=np.arange(0, 10), interval=200)
    if len(sys.argv) > 1 and sys.argv[1] == 'save':
        anim.save('line.gif', dpi=80, writer='imagemagick')
    else:
        # plt.show() 会一直循环播放动画
        plt.show()
        
 
from moviepy.video.io.bindings import mplfig_to_npimage
import moviepy.editor as mpy       
f = plt.figure(figsize=(8, 8))


fig = plt.figure()
ax1 = fig.add_axes([0.1,0.1,0.8,0.8])

map = Basemap(llcrnrlon=116,llcrnrlat=38.5,urcrnrlon=119,urcrnrlat=40.3,
             resolution='l', projection='cyl', lat_0 = 39,lon_0=117.5,ax=ax1)

shp_info = map.readshapefile("/Users/vicky/Documents/code/python/CHN_adm_shp/CHN_adm3",'states',drawbounds=True) # CHN_adm1的数据是中国各省区域

x,y=map(data1[:,0],data1[:,1]) 
l=data1[:,2] 

# 画出一开始的散点图。
#plot,=map.plot(x,y,'o',color='r',markersize=4)


# 接受一个时间参数,
def make_frame_mpl(t):
    map.plot(x,y,'o',color='r',markersize=t)
    return mplfig_to_npimage(f)
                # 所有的图像都在同一个figure上

animation = mpy.VideoClip(make_frame_mpl
                          ,duration=30)
#animation.write_gif("animation-94a2c1ff.gif", fps=20)
        # 这样其实就可以做一个动态图出来了;
    



import numpy as np 
import matplotlib.pyplot as plt 
import matplotlib.animation as animation 
#第一个参数必须为framenum 
def update(num, data, line):
  plt.plot([],[], 'bo',markersize=num)
  line.set_data(data[...,:num]) 
  #line.set_data(data[...,:num])
  return line, 
fig1 = plt.figure() 
data = np.random.rand(2, 15) 
l, = plt.plot([],[], 'bo',markersize=12) 
plt.xlim(0, 1) 
plt.ylim(0, 1) 
#plt.xlabel('x') 
#plt.title('test') 
#framenum从1增加大25后,返回再次从1增加到25,再返回... 
line_ani = animation.FuncAnimation(fig1, update, 25,fargs=(data, l),interval=50, blit=True) 
#等同于 
#line_ani = animation.FuncAnimation(fig1, update_line, frames=25,fargs=(data, l), 
#  interval=50, blit=True) 
#忽略frames参数,framenum会从1一直增加下去知道无穷 
#由于frame达到25以后,数据不再改变,所以你会发现到达25以后图形不再变化了 
#line_ani = animation.FuncAnimation(fig1, update_line, fargs=(data, l),
#  interval=50, blit=True) 
plt.show()     
    



import matplotlib.pyplot as plt
from matplotlib.patches import Circle
import numpy as np
import math
    
plt.close()  #clf() # 清图  cla() # 清坐标轴 close() # 关窗口
fig=plt.figure()
ax=fig.add_subplot(1,1,1)
ax.axis("equal") #设置图像显示的时候XY轴比例
plt.grid(True) #添加网格
plt.ion()  #interactive mode on
IniObsX=0000
IniObsY=4000
IniObsAngle=135
IniObsSpeed=10*math.sqrt(2)   #米/秒
print('开始仿真')
try:
    for t in range(180):
        #障碍物船只轨迹
        obsX=IniObsX+IniObsSpeed*math.sin(IniObsAngle/180*math.pi)*t
        obsY=IniObsY+IniObsSpeed*math.cos(IniObsAngle/180*math.pi)*t
        ax.scatter(obsX,obsY,c='b',marker='.')  #散点图
        #ax.lines.pop(1)  删除轨迹
        #下面的图,两船的距离
        plt.pause(0.001)
except Exception as err:
    print(err)

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值