2

Can't get the 3D text working to annotate the scatter plot points.

Tried Axes3D.text, plt.text but keep getting 'missing required positional argument 's'. How do you annotate in 3D in a loop?

from mpl_toolkits.mplot3d import Axes3D 
import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse
import pandas as pd
import numpy as np

df = pd.read_csv (r'J:\Temp\Michael\Python\9785.csv')

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

#Scatter plot
for i in df.index:
    x = df.at[i,'x']
    y = df.at[i,'y']
    z = df.at[i,'h']
    ax.scatter(xs=x, ys=y, zs=z, s=20,color='red',marker='^')
    label = df.at[i,'to']
    Axes3D.text(x+0.8,y+0.8,z+0.8, label, zdir=x)

TypeError: text() missing 1 required positional argument: 's'

Sheldore
  • 35,129
  • 6
  • 43
  • 58
M.Lord
  • 101
  • 10
  • Possible duplicate of [Matplotlib: Annotating a 3D scatter plot](https://stackoverflow.com/questions/10374930/matplotlib-annotating-a-3d-scatter-plot) – Sheldore May 24 '19 at 13:04
  • [Here](https://matplotlib.org/gallery/mplot3d/text3d.html) is the official documentation – Sheldore May 24 '19 at 13:04
  • @Sheldore thanks I've been checking those and trying to come right, but can't get it to work somehow... – M.Lord May 24 '19 at 13:06
  • Provide some initial lines of your dataframe so that we can run your code – Sheldore May 24 '19 at 13:27
  • problem was with the figure type - fig.gca() fixed it – M.Lord May 24 '19 at 13:27
  • You can post the solution as a self-answer and then accept it. This will help the potential future readers of your question. – Sheldore May 24 '19 at 13:38

1 Answers1

3

Changing: ax = fig.add_subplot(111, projection='3d')

to: ax = fig.gca(projection='3d')

solved the problem. Used ax.text.

from mpl_toolkits.mplot3d import Axes3D 
import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse
import pandas as pd
import numpy as np

df = pd.read_csv (r'J:\Temp\Michael\Python\9785.csv')

fig = plt.figure()
ax = fig.gca(projection='3d')

#Scatter plot
for i in df.index:
    df.set_index('to')
    x = df.at[i,'x']
    y = df.at[i,'y']
    z = df.at[i,'h']
    ax.scatter(xs=x, ys=y, zs=z, s=20,color='red',marker='^')
    ax.text(x+0.8,y+0.8,z+0.8, df.at[i,'to'], size=10, zorder=1)
M.Lord
  • 101
  • 10