adding annotation to data points

  • Last Update :
  • Techknowledgy :
<span style="color: #ffdc5c"><b>MANAGEMENT:</b></br> Gaming managers</span><br>

<img src="https://public.flourish.studio/uploads/eb9912a9-2a55-429b-bd93-685576f51d90.png" style="width: 200px" />

Suggestion : 2

This post provides several examples with reproducible code showing how to use text() function of matplotlib to add text annotations on the plot.,Once you have created the dataset and plotted the scatterplot with the previous code, you can use text() function of matplotlib to add annotation. The following parameters should be provided:,x : positions of points on the X axis,You can create a basic scatterplot using regplot() function of seaborn library. The following parameters should be provided:

import pandas as pd
import numpy as np
import matplotlib.pylab as plt
import seaborn as sns

# Create dataframe
df = pd.DataFrame({
   'x': [1, 1.5, 3, 4, 5],
   'y': [5, 15, 5, 10, 2],
   'group': ['A', 'other group', 'B', 'C', 'D']
})

sns.regplot(data = df, x = "x", y = "y", fit_reg = False, marker = "+", color = "skyblue")

plt.show()
# basic plot
sns.regplot(data = df, x = "x", y = "y", fit_reg = False, marker = "o", color = "skyblue", scatter_kws = {
   's': 400
})

# add text annotation
plt.text(3 + 0.2, 4.5, "An annotation", horizontalalignment = 'left', size = 'medium', color = 'black', weight = 'semibold')

plt.show()
# basic plot
sns.regplot(data = df, x = "x", y = "y", fit_reg = False, marker = "o", color = "skyblue", scatter_kws = {
   's': 400
})

# add annotations one by one with a loop
for line in range(0, df.shape[0]):
   plt.text(df.x[line] + 0.2, df.y[line], df.group[line], horizontalalignment = 'left', size = 'medium', color = 'black', weight = 'semibold')

plt.show()

Suggestion : 3

When we're communicating data like this, it is often useful to annotate certain features of the plot to draw the reader's attention. This can be done manually with the plt.text/ax.text command, which will place text at a particular x/y value:,Notice now that if we change the axes limits, it is only the transData coordinates that will be affected, while the others remain stationary:,In the previous example, we have anchored our text annotations to data locations. Sometimes it's preferable to anchor the text to a position on the axes or figure, independent of the data. In Matplotlib, this is done by modifying the transform.,The average user rarely needs to worry about the details of these transforms, but it is helpful knowledge to have when considering the placement of text on a figure. There are three pre-defined transforms that can be useful in this situation:

% matplotlib inline
import matplotlib.pyplot as plt
import matplotlib as mpl
plt.style.use('seaborn-whitegrid')
import numpy as np
import pandas as pd
births = pd.read_csv('data/births.csv')

quartiles = np.percentile(births['births'], [25, 50, 75])
mu, sig = quartiles[1], 0.74 * (quartiles[2] - quartiles[0])
births = births.query('(births > @mu - 5 * @sig) & (births < @mu + 5 * @sig)')

births['day'] = births['day'].astype(int)

births.index = pd.to_datetime(10000 * births.year +
   100 * births.month +
   births.day, format = '%Y%m%d')
births_by_date = births.pivot_table('births',
   [births.index.month, births.index.day])
births_by_date.index = [pd.datetime(2012, month, day)
   for (month, day) in births_by_date.index
]
fig, ax = plt.subplots(figsize = (12, 4))
births_by_date.plot(ax = ax);
fig, ax = plt.subplots(figsize = (12, 4))
births_by_date.plot(ax = ax)

# Add labels to the plot
style = dict(size = 10, color = 'gray')

ax.text('2012-1-1', 3950, "New Year's Day", ** style)
ax.text('2012-7-4', 4250, "Independence Day", ha = 'center', ** style)
ax.text('2012-9-4', 4850, "Labor Day", ha = 'center', ** style)
ax.text('2012-10-31', 4600, "Halloween", ha = 'right', ** style)
ax.text('2012-11-25', 4450, "Thanksgiving", ha = 'center', ** style)
ax.text('2012-12-25', 3850, "Christmas ", ha = 'right', ** style)

# Label the axes
ax.set(title = 'USA births by day of year (1969-1988)',
   ylabel = 'average daily births')

# Format the x axis with centered month labels
ax.xaxis.set_major_locator(mpl.dates.MonthLocator())
ax.xaxis.set_minor_locator(mpl.dates.MonthLocator(bymonthday = 15))
ax.xaxis.set_major_formatter(plt.NullFormatter())
ax.xaxis.set_minor_formatter(mpl.dates.DateFormatter('%h'));
fig, ax = plt.subplots(facecolor = 'lightgray')
ax.axis([0, 10, 0, 10])

# transform = ax.transData is the
default, but we 'll specify it anyway
ax.text(1, 5, ". Data: (1, 5)", transform = ax.transData)
ax.text(0.5, 0.1, ". Axes: (0.5, 0.1)", transform = ax.transAxes)
ax.text(0.2, 0.2, ". Figure: (0.2, 0.2)", transform = fig.transFigure);
ax.set_xlim(0, 2)
ax.set_ylim(-6, 6)
fig