可以“关闭"吗?为 Matplotlib 虚线设置颜色? [英] Can the "off" color be set for a Matplotlib dashed line?

查看:31
本文介绍了可以“关闭"吗?为 Matplotlib 虚线设置颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用虚线很不错,因为它提供了一种区分线的方法,该线不依赖于读者能够感知颜色的差异.麻烦的是,它们仅在线条的细节都大于虚线图案时才起作用.Matplotlib 的文档 Axes.plot 函数描述如何自定义线条的颜色(使用 color 关键字)以及如何自定义破折号的样式( dash 关键字).有没有办法通过一次调用 Axes.plot 来让绘图在两种不同的可选颜色之间交替,而不是有"和没有"?

我可以通过两次绘制同一条线,一次是用实线,然后用虚线重叠绘制相同的数据来达到这种效果,但这会使管理alpha透明度变得复杂(当有多条相交的线时,最好使用半透明的线在一个情节上).下图中的黑线和灰线是用这些代码行生成的:

  ax.plot(xv1,yv1,marker ="None",linestyle =-",color =(0.8,0.8,0.8,1.0))ax.plot(xv1,yv1,marker ="None",linestyle =-",color =(0.0,0.0,0.0,1.0))

希望通过一次调用 Axis.plot 就可以做到这一点的另一个原因是它会在创建图例时正确显示示例行(我发现的唯一剩余缺点答案中给出的方法).

解决方案

只需调用一次 Axes.plot"就无法完成您的要求,但可以通过使用两个自定义的

linestyle 规范为(offset,(on_off_seq)),其中 on_off_seq 是一个或多个的 tuple 更多值,以 pt s为单位.

Using dashed lines is nice because it gives a way to distinguish lines that doesn't rely on the reader being able to perceive differences in color. The trouble is that they only work if the details of the line are all larger than the dash pattern. The documentation for Matplotlib's Axes.plot function describes how to customize a line's color (with the color keyword) and how to customize the pattern of dashes (dash keyword). Is there a way to make the plot alternate between two different selectable colors instead of "there" and "not" with a single call to Axes.plot?

I can achieve this effect by plotting the same line twice, once with a solid line and then overplotting the same data with the dashed line, but that makes managing the alpha transparency complicated (translucent lines are desirable when there are several intersecting lines on one plot). The black and grey lines in the plot below were generated with these lines of code:

ax.plot(xv1, yv1, marker="None", linestyle="-", color=(0.8, 0.8, 0.8, 1.0))
ax.plot(xv1, yv1, marker="None", linestyle="--", color=(0.0, 0.0, 0.0, 1.0))

Edit: Another reason to desire that this be doable with a single call to Axis.plot is that it would display an example line correctly when creating a legend (the only remaining drawback I've found of the methods given in the answers).

解决方案

This doesn't accomplish what you are asking "with a single call to Axes.plot", but the desired behavior can be created by using two custom linestyles - one of which is offset by the width of the other's dash.

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, np.pi*4, 100)
y = np.sin(x)

plt.plot(x, y, linestyle=(0, (2, 2)))
plt.plot(x, y, linestyle=(2, (2, 2)))
plt.show()

The linestyle specification is (offset, (on_off_seq)) where on_off_seq is a tuple of one or more values, in pts.

这篇关于可以“关闭"吗?为 Matplotlib 虚线设置颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆