Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlib - How to make the marker face color transparent without making the line transparent

I know how to set the transparency of a line in matplotlib. For example, the following code makes the line and the markers transparent.

import numpy as np import matplotlib.pyplot as plt  vec = np.random.uniform(0, 10, 50) f = plt.figure(1) ax = f.add_subplot(111) ax.plot(vec, color='#999999', marker='s', alpha=0.5) 

I want line's alpha=1.0, and marker's face color to be semi-transparent (alpha=0.5). Can this be done in matplotlib?

Thank you.

like image 469
Curious2learn Avatar asked Apr 10 '13 14:04

Curious2learn


People also ask

How do I change the marker color in Matplotlib?

All of the line properties can be controlled by keyword arguments. For example, you can set the color, marker, linestyle, and markercolor with: plot(x, y, color='green', linestyle='dashed', marker='o', markerfacecolor='blue', markersize=12).

How do I change the transparency of a line in Matplotlib?

Matplotlib allows you to adjust the transparency of a graph plot using the alpha attribute. If you want to make the graph plot more transparent, then you can make alpha less than 1, such as 0.5 or 0.25. If you want to make the graph plot less transparent, then you can make alpha greater than 1.


2 Answers

See @Pelson's answer below for the correct way to do this with one line.

You can do this in a hacky way by sticky taping together two independent Line2D objects.

th = np.linspace(0, 2 * np.pi, 64) y = np.sin(th) ax = plt.gca()  lin, = ax.plot(th, y, lw=5) mark, = ax.plot(th, y, marker='o', alpha=.5, ms=10)  ax.legend([(lin, mark)], ['merged']) plt.draw() 

demo figure

see here for explanation

like image 53
tacaswell Avatar answered Sep 30 '22 11:09

tacaswell


After reading the source code of matplotlib.line, it turns out there is a code path (at least in Agg, but probably all backends) which allows you to do this. Whether this was ever intentional behaviour, I'm not sure, but it certainly works at the moment. The key is not to define an alpha value for the line, but to define the colours desired along with an alpha value:

import matplotlib.pyplot as plt  plt.plot([0, 1], [1, 0], 'k') # Do not set an alpha value here l, = plt.plot(range(10), 'o-', lw=10, markersize=30)  l.set_markerfacecolor((1, 1, 0, 0.5)) l.set_color('blue')  plt.show() 

These can probably be given as arguments in plt.plot, so just

plt.plot(range(10), 'bo-', markerfacecolor=(1, 1, 0, 0.5), ) 

will do the trick.

HTH

like image 41
pelson Avatar answered Sep 30 '22 10:09

pelson