简体   繁体   中英

How to annotate two values, one inside and one outside the bubble for matplotlib scatterplot

I've following sample example that scatter plots fruit count by their rank as bubble plot. I can get it to annotate through and outside bubble.
Sample Code:

import matplotlib.pyplot as plt
import numpy as np

fruit_name = ["Apple", "Pear", "Orange", "Banana", "Strawberry"]
fruit_count = [10000, 8000, 5000, 2000, 1000 ]
fruit_rank = [1, 2, 3, 4, 5]

#create scatter plot
fig, ax = plt.subplots()
ax.scatter(fruit_rank,fruit_count,s=fruit_count,marker='o', c=fruit_rank)

#label each bubble
for i in range(len(fruit_rank)):
    plt.annotate("({}) {}".format(i+1,fruit_name[i]),xy=(fruit_rank[i], fruit_count[i]))

#Label axis
plt.xlabel('fruit Count')
plt.ylabel(' fruit Rank')
plt.show()

Plot as below : 在此处输入图片说明

Question Is it possible to annotate two values to each bubble?
Ideally I would like to do following.

1) Have rank (1..5) annotated inside respective bubble.
2) Name of Fruit to appear on top of each bubble.

If not at least how do I annotate inside bubble such that values (eg rank number or name ) falls at the center of each bubble?

Many thanks.

You may sure create two annotations. One with the rank in the center of the bubble, and one with the name on top of it. For the rank, you may simply put horizontal and vertical alignment as "center" . For the name you may use an offset, which is half the squareroot of the bubble size in vertical direction.

import matplotlib.pyplot as plt
import numpy as np

fruit_name = ["Apple", "Pear", "Orange", "Banana", "Strawberry"]
fruit_count = [10000, 8000, 5000, 2000, 1000 ]
fruit_rank = [1, 2, 3, 4, 5]

#create scatter plot
fig, ax = plt.subplots()
ax.axis([0,6,0,14000])
ax.scatter(fruit_rank,fruit_count,s=fruit_count,marker='o', c=fruit_rank)

#label each bubble
for n,c,r in zip(fruit_name,fruit_count,fruit_rank):
    plt.annotate("({})".format(r),xy=(r, c), ha="center", va="center")
    plt.annotate(n ,xy=(r, c), xytext=(0,np.sqrt(c)/2.+5), 
                 textcoords="offset points", ha="center", va="bottom")

#Label axis
plt.xlabel('fruit Rank')
plt.ylabel(' fruit Count')
plt.show()

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM