python - 过滤散点图中的正值

标签 python dictionary matplotlib filter

想象一个嵌套字典,其中第一级是日期,第二级字典将数字作为键,将与该数字对应的值作为值。我想在每个日期的正上绘制散点图,而不会丢失作为 x 轴的日期。我的意思是,如果嵌套字典(一个特定日期)没有正值(全部为零或负数),我不想丢失日期,但没有任何内容显示为日期的 y 轴值.

这是一个用于澄清的工作示例。我在这里绘制了所有内容。我想在 x 轴上保持相同的标签和距离,但 y 轴上不显示零或负值。在此示例中,我不想看到日期“2006-02-03”和“2006-04-05”上的点。任何帮助将不胜感激。

import matplotlib.pyplot as plt

dictt = {('2005-01-04', '2006-01-04'): {0: 0, 1: 3, 2: -1, 3: 5}, ('2005-02-03', '2006-02-03'): {0: 0, 1: 0, 2: 0, 3: 0},
('2005-03-07', '2006-03-07'):  {0: -3, 1: 0, 2: 3, 3: 5}, ('2005-04-06', '2006-04-05'):  {0: -2, 1: -3, 2: -1, 3: -2}}

for k in list(dictt.keys()):
    for i in range(4):
        plt.scatter(k[1], dictt[k[0], k[1]][i])

enter image description here

最佳答案

您最喜欢什么底线?零(我的偏好)还是绘制值的最小值?我已经提供了两种解决方案!

此外,我提供了一个根据n参数的值来标记点的解决方案。我认为这是一个进步,你觉得怎么样?

enter image description here

这是代码,它有点复杂,因为,哦,你的数据格式很复杂。

import matplotlib.pyplot as plt

dictt = {('2005-01-04', '2006-01-04'): {0:  0, 1:  3, 2: -1, 3:  5},
         ('2005-02-03', '2006-02-03'): {0:  0, 1:  0, 2:  0, 3:  0},
         ('2005-03-07', '2006-03-07'): {0: -3, 1:  0, 2:  3, 3:  5}, 
         ('2005-04-06', '2006-04-05'): {0: -2, 1: -3, 2: -1, 3: -2}}

dates = [k[1] for k in dictt.keys()]

by_n = {} # reorder data according to the second layer of ordinality
for (d0, d1), d in dictt.items():
        for n in d.keys():
            if n not in by_n: by_n[n] = [] # empty list
            by_n[n].append((d1, d[n] if d[n]>0 else None))

fig, (ax0, axmin) = plt.subplots(ncols=2, figsize=(8,3), layout='constrained')

# first, using 0 as the bottom line    
for n, by_date in by_n.items(): ax0.scatter(*zip(*by_date), label='n=%d'%n)
for day in dates: ax0.scatter(day, 0, s=0)
ax0.legend()

# next, using the minimum value, that of course we must compute 
min_val = min([n for d in dictt.values() for n in d.values if n>0])
for n, by_date in by_n.items(): axmin.scatter(*zip(*by_date), label='n=%d'%n)
for day in dates: axmin.scatter(day, min_val, s=0)
axmin.legend()

plt.show()

关于python - 过滤散点图中的正值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76204576/

相关文章:

python - 时间轴精确绘图

dictionary - 反转 f# Map <'a,Map<' b ,'T>>) -> Map<' b,Map <'a,' T>> 中的嵌套字典

python matplotlib 用相同的参数绘制许多子图

python - numpy 矩阵和 numpy.matrixlib.defmatrix.matrix 之间有什么区别?

python - scikit-learn分区数据中的LassoCV如何实现?

python - 在嵌套的python dict中查找所有出现的键

python - 为 pandas 中数据框的列的组合创建字典

python - 如何为 x 轴上的刻度设置动画?

Python单元测试失败: should raise value error but not

python - 显示另一列,其中条件在其他列中确定