Arrow direction to python

I am trying to annotate a scatter plot in Python 2.7 using Matplotlib. Here is the graph code:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

df = pd.DataFrame(np.random.rand(5,3), columns=list('ABC'))
df.insert(0,'Annotation_Text',['ABC','DEF','GHI','JKL','mnop'])

q = 2
pqr = 1

# Scatter Plot:
x = df['A']
y = df.iloc[:,q]
plt.scatter(x, y, marker='o', label = df.columns.tolist()[q])

# Plot annotation:
plt.annotate(df.iloc[pqr,0]+', (%.2f, %.2f)' % (x.ix[pqr],y.ix[pqr]), xy=(x.ix[pqr], y.ix[pqr]), xycoords='data', xytext = (x.ix[pqr], y.ix[pqr]), textcoords='offset points', arrowprops=dict(arrowstyle='-|>'))

# Axes title/legend:
plt.xlabel('xlabel', fontsize=18)
plt.ylabel('ylabel', fontsize=16)
plt.legend(scatterpoints = 1)

plt.show()

      

As you can see, the main line is the line that starts with plt.annotate(df.iloc[pqr,0]+', (%...............

.

I think that the main problem lies in this part of the line plt.annotate()

: xytext = (x.ix[pqr], y.ix[pqr]), textcoords='offset points', arrowprops=dict(arrowstyle='-|>')

. Hence, it xytext = (x.ix[pqr], y.ix[pqr])

is just a tuple of the x and y coordinates of the data point to be annotated. Unfortunately this puts the annotation right at the data point, which is not what I want. I want to leave a space between the data point and the annotation text.

Also, I am having a problem with the arrow and annotation to this line. See below. Annotation Image

Problems:

  • Currently, the annotation text overlaps the arrow. The annotation text is too close to the data point. I don't want it to be this close.
  • Also the arrow points from right to left. I don't think I asked him to plot the arrow from right to left, so I don't know why it draws the arrow in that direction.

Is there a way to control the text annotation so that there is no overlap with the data point? Also, how do I change the direction of the arrow from right to left in direction a) best

or b) from left to right?

+3


source to share


1 answer


B plt.annotate(...)

, xy

specifies the position of the data you want to point to (one end of the arrow), and the xytext

position of your text. In your code, they overlap because you specified the same positions for xy

and xytext

. Try this instead (for example):

plt.annotate(df.iloc[pqr,0]+', (%.2f, %.2f)' % (x.ix[pqr], y.ix[pqr]), xy=(x.ix[pqr], y.ix[pqr]), xycoords='data', xytext=(x.ix[pqr], y.ix[pqr]+0.3), arrowprops=dict(arrowstyle='-|>'), horizontalalignment='center')

      



The default arrow points from text to data point. If you want to change the direction of the arrow, you can usearrowprops=dict(arrowstyle='<|-')

+1


source







All Articles