散点图字典

2024-06-16 08:59:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要散点画一本字典。在

我的数据如下:

{'+C': {1: 191, 2: 557}, '+B': None, '-B': None, '+D': None, '+N': {1: 1, 3: 1}, '+L': {1: 2819, 2: 1506}, '>L': None, '<C': {0: 2125}, '<B': None, '<L': {0: 2949, 1: 2062}}

外部关键点是x轴标签,内侧关键点是y轴。内部键的值是x,y的注释。我试着绘制数据,但是没有得到我想要的图形。在

我尝试了以下方法,但最终在x轴上重复了几次。在

^{pr2}$

Tags: 数据方法none图形字典绘制标签关键点
1条回答
网友
1楼 · 发布于 2024-06-16 08:59:53

您需要为x设置整数类别,然后可以在x轴上分配标签。下面的代码使用您dict中的操作代码。注意,python中的字典是无序的,因此需要对键进行排序。您可以改为使用有序dict,然后使用数字键()直接。在

每个点的注释都是字符串,每次放置一个,并在绘图上添加文本注释。我们需要用plt.轴()因为自动计算范围时不包括注释。在

import matplotlib.pyplot as plt

action_sequence = {
    '+C': {1: 191, 2: 557}, '+B': None, '-B': None, '+D': None, 
    '+N': {1: 1, 3: 1}, '+L': {1: 2819, 2: 1506}, 
    '>L': None, '<C': {0: 2125}, '<B': None, '<L': {0: 2949, 1: 2062}
}

# x data are categorical; define a lookup table mapping category string to int
x_labels = list(sorted(action_sequence.keys()))
x_values = list(range(len(x_labels)))
lookup_table = dict((v,k) for k,v in enumerate(x_labels))

# Build a list of points (x, y, annotation) defining the scatter plot.
points = [(lookup_table[action], key, anno)
      for action, values in action_sequence.items()
      for key, anno in (values if values else {}).items()]
x, y, anno = zip(*points)

# y is also categorical, with integer labels for the categories
y_values = list(range(min(y), max(y)+1))
y_labels = [str(v) for v in y_values]

plt.figure(figsize=(10,8))
plt.title('Scatter Plot', fontsize=20)
plt.xlabel('x', fontsize=15)
plt.ylabel('y', fontsize=15)
plt.xticks(x_values, x_labels)
plt.yticks(y_values, y_labels)
plt.axis([min(x_values)-0.5, max(x_values)+0.5, 
          min(y_values)-0.5, max(y_values)+0.5])
#plt.scatter(x, y, marker = 'o')
for x_k, y_k, anno_k in points:
    plt.text(x_k, y_k, str(anno_k))

plt.show()

有关散点图标记的不同方法,请参见以下问题:

Matplotlib: How to put individual tags for a scatter plot

相关问题 更多 >