4

I'm having trouble changing the background of my 3d graph to black. This is my current code. When I do set facecolor to black, it changes the inside of the graph to be grey, which is not what I want.

enter image description here

fig = plt.figure()
fig.set_size_inches(10,10)
ax = plt.axes(projection='3d')
ax.grid(False)
ax.xaxis.pane.set_edgecolor('b')
ax.yaxis.pane.set_edgecolor('b')
ax.zaxis.pane.set_edgecolor('b')

# plt.gca().patch.set_facecolor('white')
# plt.axis('On')
fig.patch.set_facecolor('black')

ax.scatter(xs = Z['PC1'], ys = Z['PC2'], zs = Z['PC3'], c = Z['color'], s = 90, depthshade= False)
ax.set(title = 'test', xlabel = 'PC1', ylabel = 'PC2', zlabel = 'PC3')
filippo
  • 5,197
  • 2
  • 21
  • 44
Ryan Tom
  • 195
  • 3
  • 14

2 Answers2

10

If you want to keep the wireframe axis you can do

ax.w_xaxis.pane.fill = False
ax.w_yaxis.pane.fill = False
ax.w_zaxis.pane.fill = False

Here's a complete example:

fig = plt.figure()
ax = plt.axes(projection='3d')
x, y, z = np.random.randint(10, size=(3, 250))

ax.scatter(x, y, z, c=np.random.randn(250))

fig.set_facecolor('black')
ax.set_facecolor('black') 
ax.grid(False) 
ax.w_xaxis.pane.fill = False
ax.w_yaxis.pane.fill = False
ax.w_zaxis.pane.fill = False

enter image description here

Or you can hide them altogether with

ax.w_xaxis.set_pane_color((0.0, 0.0, 0.0, 0.0))
ax.w_yaxis.set_pane_color((0.0, 0.0, 0.0, 0.0))
ax.w_zaxis.set_pane_color((0.0, 0.0, 0.0, 0.0))

Complete example:

fig = plt.figure()
ax = plt.axes(projection='3d')
x, y, z = np.random.randint(10, size=(3, 250))

ax.scatter(x, y, z, c=np.random.randn(250))

fig.set_facecolor('black')
ax.set_facecolor('black')
ax.grid(False)
ax.w_xaxis.set_pane_color((0.0, 0.0, 0.0, 0.0))
ax.w_yaxis.set_pane_color((0.0, 0.0, 0.0, 0.0))
ax.w_zaxis.set_pane_color((0.0, 0.0, 0.0, 0.0))

enter image description here

filippo
  • 5,197
  • 2
  • 21
  • 44
2

Use Matplotlib's dark background style sheet, which uses white for elements that are typically black (text, borders, etc). It also works for 3D plots.

enter image description here

import numpy as np
import matplotlib.pyplot as plt


plt.style.use('dark_background')

fig, ax = plt.subplots()

L = 6
x = np.linspace(0, L)
ncolors = len(plt.rcParams['axes.prop_cycle'])
shift = np.linspace(0, L, ncolors, endpoint=False)
for s in shift:
    ax.plot(x, np.sin(x + s), 'o-')
ax.set_xlabel('x-axis')
ax.set_ylabel('y-axis')
ax.set_title("'dark_background' style sheet")

plt.show()
crypdick
  • 16,152
  • 7
  • 51
  • 74