ChitaWang 2022-08-08 16:49 采纳率: 20%
浏览 139
已结题

python matplotlib画图时,刻度线被图中曲线遮挡,刻度线无法置于最顶层

python matplotlib画图时,刻度被图中曲线遮挡无法修改

我的代码如下:

import pandas as pd
import os
import numpy as np
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
from cartopy.mpl.ticker import LongitudeFormatter, LatitudeFormatter
import cartopy.io.shapereader as shpreader
import cartopy.feature as cfeat
import warnings
warnings.filterwarnings('ignore')
file = r'C:\Users\16374\Desktop\123\yanyixia\0630\footprint\typhon.csv'
df = pd.read_csv(file) #读取以后就是数据框形式
# print(df['name'])
# print(type(df))
# 创建路径图背景
fig = plt.figure(dpi=600)
fig.patch.set_facecolor('none')#画布透明
# plt.rcParams['ytick.direction'] = 'in'  # 刻度线内向 要放在画图前,否则会失效
# plt.rcParams['xtick.direction'] = 'in' # 刻度线内向
plt.rcParams['font.sans-serif']=['SimHei']
plt.rcParams['axes.unicode_minus'] = False # 设置支持负号显示
# box = [117, 127, 30, 42] #黄渤海
box = [110, 180, 20, 50]
xstep, ystep = 10, 10  # 横纵坐标刻度间隔
ax = fig.add_subplot(1, 1, 1, projection=ccrs.PlateCarree())
ax.set_extent(box, crs=ccrs.PlateCarree())  # set_extent需要配置相应的crs,否则出来的地图范围不准确
# ax.tick_params(axis='both', tickdir='in', zorder = 10) #labelrotation=20 坐标刻度线in:朝里,out:朝外,inout:居中,'both'X,Y轴,axis=’x‘
# ax.set_title(titles, fontsize=20)  # 添加标题
SHP = r'D:\ProgramData\Anaconda3\Lib\site-packages\cartopy\data\shapefiles\natural_earth\china_shp'
SHP1 = r'D:\ProgramData\Anaconda3\Lib\site-packages\cartopy\data\shapefiles\natural_earth\中国GIS地图\国家基础地理数据\hyd1_4m'
# 添加地图底图
ax.add_geometries(shpreader.Reader(os.path.join(SHP, 'country1.shp')).geometries(),
                  ccrs.PlateCarree(), facecolor='none', edgecolor='k', linewidth=0.7, zorder=3)  # 全球国界
ax.add_geometries(shpreader.Reader(os.path.join(SHP, 'cnhimap.shp')).geometries(),
                  ccrs.PlateCarree(), facecolor='none', edgecolor='k', linewidth=0.7, zorder=3)  # 中国省界
ax.add_feature(cfeat.LAND.with_scale('50m'), color = 'white', zorder=1)  #陆地和海洋颜色区分 color = 'none':透明色,只有设置为顺序1,刻度才不会被遮挡
ax.add_geometries(shpreader.Reader(os.path.join(SHP1, 'hyd1_4l.shp')).geometries(),
                  ccrs.PlateCarree(), facecolor='none', edgecolor='blue', linewidth=0.7, zorder=3)  # 中国河流
# zero_direction_label用来设置经度的0度加不加E和W
lon_formatter = LongitudeFormatter(zero_direction_label=False)
lat_formatter = LatitudeFormatter()
ax.xaxis.set_major_formatter(lon_formatter)
ax.yaxis.set_major_formatter(lat_formatter)
# # 添加网格线
# ax.grid()
# ax.gridlines(linestyle = '--', zorder = 4)
# 标注坐标轴
ax.set_yticks(np.arange(box[2], box[3] + ystep, ystep), crs=ccrs.PlateCarree())
ax.set_xticks(np.arange(box[0], box[1] + xstep, xstep), crs=ccrs.PlateCarree())
# ax.tick_params(axis='both', tickdir='in', zorder = 10) #labelrotation=20 坐标刻度线in:朝里,out:朝外,inout:居中,'both'X,Y轴,axis=’x‘
ax.tick_params(labelsize = 8) #刻度标签的字体大小
#添加黄渤海范围的红框
left_x = 117
bottom_left_y = 30
width = 10
height = 12
rect = plt.Rectangle((left_x, bottom_left_y), width, height, linestyle = '--',
                     fill=False, edgecolor = 'red', linewidth = 1, zorder = 5)
ax.add_patch(rect)
plt.minorticks_on()
plt.tick_params(which='minor', top=True, right = True, direction='in', zorder = 10)
plt.tick_params(which='major', direction='in', zorder = 10) #width=2, length=4,

"""
画布底图完成
读取台风路径数据
"""
m,n =np.shape(df) #m为行数,n为列数
lat = []
lon = []
count = 1 #台风计数
for i in range(0, m):
    if i == 0: #第一行是列名,不要
        continue
    elif i == 1: #第一个台风的数据需要麻烦点,预先读一行数据方便后面比较是不是同一个台风名
        tname = df['name'][i]
        lat.append(df['lat'][i])
        lon.append(df['lon'][i])
    else:
        if tname == df['name'][i]:
            lat.append(df['lat'][i])
            lon.append(df['lon'][i])
        else: #同一个台风的数据读完了,接下来读新的台风数据
            count = count + 1
            if i < m:
                # 先把这一个台风的图画了
                # print(lat,lon)
                ax.plot(lon, lat, color='green', alpha = 0.5, linewidth = 0.4, zorder = 3)
                lat = []
                lon = []
                tname = df['name'][i]
                lat.append(df['lat'][i])
                lon.append(df['lon'][i])
            elif i == m:
                ax.plot(lon, lat, color='green', alpha = 0.5, linewidth = 0.4, zorder = 3)
# plt.pot()
print('1993-2020年间,西北太平洋录得台风数:', count)
plt.savefig('路径.jpg', dpi=600, bbox_inches='tight', transparent=True, pad_inches=0.1)  # 输出地图,并设置边框空白紧密 # bbox_inches='tight' 图片边界空白紧致, 背景透明
# plt.show()

从下面出的图可以看出,图中曲线是会把我的刻度线挡住的,左下角相当明显,不知道怎么解决。

img

关于刻度设置的代码我试过好多种了,都不行,下面是我用过的方法:
###第一种,开头设置,不行,刻度被挡
plt.rcParams['ytick.direction'] = 'in'  # 刻度线内向 要放在画图前,否则会失效
plt.rcParams['xtick.direction'] = 'in' # 刻度线内向
#第二种,添加了zorder,刻度还是被图中折线挡了
ax.tick_params(axis='both', tickdir='in', zorder = 10) 
#第三种,折现依然会把刻度挡住
plt.minorticks_on()
plt.tick_params(which='minor', top=True, right = True, direction='in', zorder = 10)
plt.tick_params(which='major', direction='in', zorder = 10) #width=2, length=4,
我想让刻度置于最顶层,图中内容不会挡住我的刻度线,请问有什么解决方法吗?
  • 写回答

0条回答 默认 最新

    报告相同问题?

    问题事件

    • 系统已结题 8月16日
    • 创建了问题 8月8日

    悬赏问题

    • ¥15 is not in the mmseg::model registry。报错,模型注册表找不到自定义模块。
    • ¥15 安装quartus II18.1时弹出此error,怎么解决?
    • ¥15 keil官网下载psn序列号在哪
    • ¥15 想用adb命令做一个通话软件,播放录音
    • ¥30 Pytorch深度学习服务器跑不通问题解决?
    • ¥15 部分客户订单定位有误的问题
    • ¥15 如何在maya程序中利用python编写领子和褶裥的模型的方法
    • ¥15 Bug traq 数据包 大概什么价
    • ¥15 在anaconda上pytorch和paddle paddle下载报错
    • ¥25 自动填写QQ腾讯文档收集表