0

I have a data frame with the following values and would like to create a 3D plot showing Recency, Frequency, and Monetary values labelled by the categories/loyalty levels (bronze, silver, gold, platinum) assigned to them. The relevant data looks as follows:

RFMScores.head()

enter image description here

the RFM_Catagory_Level are numeric scores associated with the loyalty level

In attempting to make the chart, I used

figrfm2 = plt.figure()
ax = Axes3D(figrfm2)

xs = RFMScores.Recency
ys = RFMScores.Frequency
zs = RFMScores.Monetary
scores = RFMScores.RFM_Catagory_Level

scatter = ax.scatter(xs, ys, zs,c=scores,cmap='tab20b')

ax.set_title("3D plot")
ax.set_xlabel('Recency')
ax.set_ylabel('Frequency')
ax.set_zlabel('Monetary')
ax.legend(*scatter.legend_elements())
plt.show()

But the legend has the numeric values instead of the actual labels.

enter image description here

When I attempt to use the RFM_Loyalty_Level such as this:

figrfm2 = plt.figure()
ax = Axes3D(figrfm2)

xs = RFMScores.Recency
ys = RFMScores.Frequency
zs = RFMScores.Monetary

scatter = ax.scatter(xs, ys, zs,c=RFMScores.RFM_Loyalty_Level,cmap='tab20b')

ax.set_title("3D plot")
ax.set_xlabel('Recency')
ax.set_ylabel('Frequency')
ax.set_zlabel('Monetary')
ax.legend(*scatter.legend_elements())
plt.show() 
 

The chart is blank with no data. How do I fix this so that I have a chart, but with the label categories "platinum, gold, silver, bronze" instead of the numeric values that are in the legend?

JLuu
  • 379
  • 1
  • 3
  • 17

1 Answers1

0

I found the solution here

The key (no pun intended) is to create a dictionary of the two columns and then pass in the handles and keys into the legend(handles=,labels=) arguments. Solution is below, but check out link for the original answer and to give credit to where it's properly due.

grouped_codes = dict(zip(RFMScores.RFM_Loyalty_Level, RFMScores.RFM_Catagory_Level))

figrfm2 = plt.figure()
ax = Axes3D(figrfm2)

xs = RFMScores.Recency
ys = RFMScores.Frequency
zs = RFMScores.Monetary
scores = RFMScores.RFM_Catagory_Level

scatter = ax.scatter(xs, ys, zs,c=scores,cmap='tab20b')
handles = scatter.legend_elements(num=[1,2,3,4])[0]

ax.set_title("3D plot")
ax.set_xlabel('Recency')
ax.set_ylabel('Frequency')
ax.set_zlabel('Monetary')
ax.legend(title="Binned RFM Scores",handles=handles,labels=grouped_codes.keys(),*scatter.legend_elements())
plt.show()

JLuu
  • 379
  • 1
  • 3
  • 17