matplotlib 一种在保持格式的同时处理图轴中重叠标签的方法

ijxebb2r  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(113)

我在python中绘制了两个图,其中X轴和Y轴标签对应于点值。由于数据点接近,标签重叠,影响可读性。
我的目标是保持每个轴标签对应于一个精确点的格式,同时确保标签不重叠。
尽管尝试了标签旋转,字体更改和类似问题的解决方案,但我无法解决这个问题。
有什么建议可以在不改变标签格式的情况下管理重叠的标签吗?也许有点麻烦,有没有一种方法可以移动轴标签中特定的重叠数字?

import matplotlib.pyplot as plt
import pandas as pd

# Given Data
data = {'v': [0.97, 0.915, 0.892, 0.847, 0.715, 0.472, 0.248, 0.1, 0.053, 0.015],
        'i': [0, 0.000915, 0.00270303, 0.00847, 0.021666667, 0.0472, 0.075151515, 0.1, 0.112765957, 0.15],
        'p': [0, 0.000837225, 0.002411103, 0.00717409, 0.015491667, 0.0222784, 0.018637576, 0.01, 0.005976596, 0.00225]}

df = pd.DataFrame(data)

# IV-curve Plot
plt.figure(figsize=(8,5))
plt.scatter(df['v'], df['i'], marker='o') 
plt.plot(df['v'], df['i'], linestyle='-', marker='o', color='b') 
plt.xticks(df['v'],rotation=45,) 
plt.yticks(df['i'],rotation=45,) 
plt.xlabel('Voltage (V)')
plt.ylabel('Current (I)')
plt.title('IV-Curve')
plt.grid(True)
plt.show()

# Power Curve Plot
plt.figure(figsize=(8,5))
plt.scatter(df['v'], df['p'], marker='o')
plt.plot(df['v'], df['p'], linestyle='-', marker='o', color='b') 
plt.xticks(df['v'],rotation=45)
plt.yticks(df['p'],rotation=45) 
plt.xlabel('Voltage (V)')
plt.ylabel('Power (P)')
plt.title('Power-Curve')
plt.grid(True)
plt.show()

字符串


的数据


jckbn6z7

jckbn6z71#

我已经写了一个函数,它删除了太靠近的滴答声。
我认为matplotlib可能通过它的tick locators支持你所请求的功能,在这种情况下,这可能是一个比下面的方法更简洁的解决方案。

import numpy as np

def remove_close_ticks(axes=None,
                       too_close_x=np.inf,
                       too_close_y=np.inf,
                       keep_final_tick=True):    
    #Ge the current axes if none are supplied
    if axes is None: axes = plt.gca()
    
    #Deal with x ticks, then y ticks
    for axis in ['x', 'y']:
        #Are we modifying the x or y axis
        if axis == 'x':
            setter = axes.set_xticks
            min_distance = too_close_x
        else:
            setter = axes.set_yticks
            min_distance = too_close_y
        
        #Get the tick values for this axis
        #And the distance between consecutive ticks
        ticks = axes.properties()[axis + 'ticks']
        diff = np.abs(np.diff(ticks))
        
        #Keep ticks that are more than the min distance
        new_ticks = ticks[np.argwhere(diff > min_distance).ravel()]
        
        #Always keep the final tick if requested
        if keep_final_tick: new_ticks = np.append(new_ticks, ticks[-1])
        setter(new_ticks)

字符串
使用方法:

#Decide what is too close for each axis
too_close_v = 0.03
too_close_i = 0.01
too_close_p = 0.005

# IV-curve Plot
.
. <your code>
.
remove_close_ticks(too_close_x=too_close_v, too_close_y=too_close_i)
plt.show() #optional

# Power Curve Plot
.
. <your code>
.
remove_close_ticks(too_close_x=too_close_v, too_close_y=too_close_p)
plt.show() #optional


的数据

相关问题