forked from alfonsosemeraro/pyplutchik
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpyplutchik.py
1326 lines (987 loc) · 40.7 KB
/
pyplutchik.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
**********
Plutchik
**********
This package contains a data visualization tool for corpora annotated with emotions.
Given a JSON representation of the Plutchik's emotions (or dyads) in a text or in a group of texts,
it draws the corresponding Plutchik's flower.
See Plutchik, Robert. "A general psychoevolutionary theory of emotion." Theories of emotion. Academic press, 1980. 3-33.
--------
repository available at https://www.github.com/alfonsosemeraro/pyplutchik
@author: Alfonso Semeraro <[email protected]>
"""
import shapely.geometry as sg
import matplotlib.pyplot as plt
import descartes
from math import sqrt, cos, sin, radians
import numpy as np
from matplotlib import colors
__author__ = """Alfonso Semeraro ([email protected])"""
__all__ = ['emo_params',
'dyad_params',
'_rotate_point',
'_polar_coordinates',
'_neutral_central_circle',
'_petal_shape_emotion',
'_petal_shape_dyad',
'_petal_spine_emotion',
'_petal_spine_dyad',
'_petal_circle',
'_draw_emotion_petal',
'_draw_dyad_petal',
'_check_scores_kind',
'plutchik']
def emo_params(emotion):
"""
Gets color and angle for drawing a petal.
Color and angle depend on the emotion name.
Required arguments:
----------
*emotion*:
Emotion's name. Possible values:
['joy', 'trust', 'fear', 'surprise', 'sadness', 'disgust', 'anger', 'anticipation']
Returns:
----------
*color*:
Matplotlib color for the petal. See: https://matplotlib.org/3.1.0/gallery/color/named_colors.html
*angle*:
Each subsequent petal is rotated 45° around the origin.
Notes:
-----
This function allows also 8 principal emotions, one for each Plutchik's flower petal.
No high or low intensity emotions are allowed (no 'ecstasy' or 'serenity', for instance).
"""
if emotion == 'joy':
color = 'gold'
angle = 0
elif emotion == 'trust':
color = 'olivedrab'
angle = -45
elif emotion == 'fear':
color = 'forestgreen'
angle = -90
elif emotion == 'surprise':
color = 'skyblue'
angle = -135
elif emotion == 'sadness':
color = 'dodgerblue'
angle = -180
elif emotion == 'disgust':
color = 'slateblue'
angle = -225
elif emotion == 'anger':
color = 'orangered'
angle = -270
elif emotion == 'anticipation':
color = 'darkorange'
angle = -315
else:
raise Exception("""Bad input: {} is not an accepted emotion.
Must be one of 'joy', 'trust', 'fear', 'surprise', 'sadness', 'disgust', 'anger', 'anticipation'""".format(emotion))
return color, angle, 0
def dyad_params(dyad):
"""
Gets colormap and angle for drawing a dyad.
Colormap and angle depend on the dyad name.
Required arguments:
----------
*dyad*:
Dyad's name. Possible values:
{"primary": ['love', 'submission', 'alarm', 'disappointment', 'remorse', 'contempt', 'aggression', 'optimism'],
"secondary": ['guilt', 'curiosity', 'despair', '', 'envy', 'cynism', 'pride', 'fatalism'],
"tertiary": ['delight', 'sentimentality', 'shame', 'outrage', 'pessimism', 'morbidness', 'dominance', 'anxiety']}
Returns:
----------
*colormap*:
Matplotlib colormap for the dyad. See: https://matplotlib.org/3.1.0/gallery/color/named_colors.html
*angle*:
Each subsequent dyad is rotated 45° around the origin.
"""
# PRIMARY DYADS
if dyad == 'love':
cmap = ['gold', 'olivedrab']
angle = -45 / 2
emos = ['joy', 'trust']
level = 1
elif dyad == 'submission':
cmap = ['olivedrab', 'forestgreen']
angle = (-45 / 2) + (-45)
emos = ['trust', 'fear']
level = 1
elif dyad == 'alarm':
cmap = ['forestgreen', 'skyblue']
angle = (-45 / 2) + (-90)
emos = ['fear', 'surprise']
level = 1
elif dyad == 'disappointment':
cmap = ['skyblue', 'dodgerblue']
angle = (-45 / 2) + (-135)
emos = ['surprise', 'sadness']
level = 1
elif dyad == 'remorse':
cmap = ['dodgerblue', 'slateblue']
angle = (-45 / 2) + (-180)
emos = ['sadness', 'disgust']
level = 1
elif dyad == 'contempt':
cmap = ['slateblue', 'orangered']
angle = (-45 / 2) + (-225)
emos = ['disgust', 'anger']
level = 1
elif dyad == 'aggressiveness':
cmap = ['orangered', 'darkorange']
angle = (-45 / 2) + (-270)
emos = ['anger', 'anticipation']
level = 1
elif dyad == 'optimism':
cmap = ['darkorange', 'gold']
angle = (-45 / 2) + (-315)
emos = ['anticipation', 'joy']
level = 1
# SECONDARY DYADS
elif dyad == 'guilt':
cmap = ['gold', 'forestgreen']
angle = -45
emos = ['joy', 'fear']
level = 2
elif dyad == 'curiosity':
cmap = ['olivedrab', 'skyblue']
angle = -90
emos = ['trust', 'surprise']
level = 2
elif dyad == 'despair':
cmap = ['forestgreen', 'dodgerblue']
angle = -135
emos = ['fear', 'sadness']
level = 2
elif dyad == 'unbelief':
cmap = ['skyblue', 'slateblue']
angle = -180
emos = ['surprise', 'disgust']
level = 2
elif dyad == 'envy':
cmap = ['dodgerblue', 'orangered']
angle = -225
emos = ['sadness', 'anger']
level = 2
elif dyad == 'cynism':
cmap = ['slateblue', 'darkorange']
angle = -270
emos = ['disgust', 'anticipation']
level = 2
elif dyad == 'pride':
cmap = ['orangered', 'gold']
angle = -315
emos = ['anger', 'joy']
level = 2
elif dyad == 'hope':
cmap = ['darkorange', 'olivedrab']
angle = 0
emos = ['anticipation', 'trust']
level = 2
# TERTIARY DYADS
elif dyad == 'delight':
cmap = ['gold', 'skyblue']
angle = (-45 / 2) + (-45)
emos = ['joy', 'surprise']
level = 3
elif dyad == 'sentimentality':
cmap = ['olivedrab', 'dodgerblue']
angle = (-45 / 2) + (-90)
emos = ['trust', 'sadness']
level = 3
elif dyad == 'shame':
cmap = ['forestgreen', 'slateblue']
angle = (-45 / 2) + (-135)
emos = ['fear', 'disgust']
level = 3
elif dyad == 'outrage':
cmap = ['skyblue', 'orangered']
angle = (-45 / 2) + (-180)
emos = ['surprise', 'anger']
level = 3
elif dyad == 'pessimism':
cmap = ['dodgerblue', 'darkorange']
angle = (-45 / 2) + (-225)
emos = ['sadness', 'anticipation']
level = 3
elif dyad == 'morbidness':
cmap = ['slateblue', 'gold']
angle = (-45 / 2) + (-270)
emos = ['disgust', 'joy']
level = 3
elif dyad == 'dominance':
cmap = ['orangered', 'olivedrab']
angle = (-45 / 2) + (-315)
emos = ['anger', 'trust']
level = 3
elif dyad == 'anxiety':
cmap = ['darkorange', 'forestgreen']
angle = (-45 / 2)
emos = ['anticipation', 'fear']
level = 3
# OPPOSITES
elif dyad == 'bittersweetness':
cmap = ['gold', 'dodgerblue']
angle = 0
emos = ['joy', 'sadness']
level = 4
elif dyad == 'ambivalence':
cmap = ['olivedrab', 'slateblue']
angle = -45
emos = ['trust', 'disgust']
level = 4
elif dyad == 'frozenness':
cmap = ['forestgreen', 'orangered']
angle = -90
emos = ['fear', 'anger']
level = 4
elif dyad == 'confusion':
cmap = ['skyblue', 'darkorange']
angle = -135
emos = ['surprise', 'anticipation']
level = 4
else:
raise Exception("""Bad input: '{}' is not an accepted name for a dyad.
Must be one of:
'love', 'submission', 'alarm', 'disappointment', 'remorse', 'contempt', 'aggressiveness', 'optimism',
'guilt', 'curiosity', 'despair', 'unbelief', 'envy', 'cynism', 'pride', 'hope',
'delight', 'sentimentality', 'shame', 'outrage', 'pessimism', 'morbidness', 'dominance', 'anxiety',
'bittersweetness', 'ambivalence', 'frozenness', 'confusion'
""".format(dyad))
return emos, cmap, angle, level
def _rotate_point(point, angle):
"""
Rotate a point counterclockwise by a given angle around a given origin.
Required arguments:
----------
*point*:
A two-values tuple, (x, y), of the point to rotate
*angle*:
The angle the point is rotated. The angle should be given in radians.
Returns:
----------
*(qx, qy)*:
A two-values tuple, the new coordinates of the rotated point.
"""
ox, oy = 0, 0
px, py = point
angle = radians(angle)
qx = ox + cos(angle) * (px - ox) - sin(angle) * (py - oy)
qy = oy + sin(angle) * (px - ox) + cos(angle) * (py - oy)
return (qx, qy)
def _polar_coordinates(ax, font, fontweight, fontsize, show_ticklabels, ticklabels_angle, ticklabels_size, offset = .15):
"""
Draws polar coordinates as a background.
Required arguments:
----------
*ax*:
Axes to draw the coordinates.
*font*:
Font of text. Default is Montserrat.
*fontweight*:
Font weight of text. Default is light.
*fontsize*:
Font size of text. Default is 15.
*show_ticklabels*:
Boolean, wether to show tick labels under Joy petal. Default is False.
*ticklabels_angle*:
How much to rotate tick labels from y=0. Value should be given in radians. Default is 0.
*ticklabels_size*:
Size of tick labels. Default is 11.
*offset*:
Central neutral circle has radius = .15, and coordinates must start from there.
Returns:
----------
*ax*:
The input Axes modified.
"""
# Lines
for i in range(0, 110, 20):
c = plt.Circle((0, 0), offset + i/100, color = 'grey', alpha = .3, fill = False, zorder = -20)
ax.add_artist(c)
# Tick labels
if show_ticklabels:
for x in np.arange(0.2, 1.2, .2):
a = round(x, 1)
x, y = _rotate_point((0, a + offset), ticklabels_angle) #-.12
ax.annotate(str(a), xy = (x, y), fontfamily = font, size = ticklabels_size, fontweight = fontweight, zorder = 8, rotation = ticklabels_angle)
return ax
def _neutral_central_circle(ax, r = .15):
"""
Draws central neutral circle (in grey).
Required arguments:
----------
*ax*:
Axes to draw the coordinates.
*r*:
Radius of the circle. Default is .15.
Returns:
----------
*ax*:
The input Axes modified.
"""
c = sg.Point(0, 0).buffer(r)
ax.add_patch(descartes.PolygonPatch(c, fc='white', ec=(.5, .5, .5, .3), alpha=1, zorder = 15))
return ax
def _outer_border(ax, emotion_score, color, angle, highlight, offset = .15, height_width_ratio = 1, normalize = False):
"""
Draw a the outer border of a petal.
Required arguments:
----------
*ax*:
Axes to draw the coordinates.
*emotion_score*:
Score of the emotion. Values range from 0 to 1.
*color*:
Color of the petal. See emo_params().
*angle*:
Rotation angle of the petal. See emo_params().
*highlight*:
String. 'opaque' if the petal must be shadowed, 'regular' is default.
*offset*:
Central neutral circle has radius = .15, and petals must start from there.
*height_width_ratio*:
Ratio between height and width of the petal. Lower the ratio, thicker the petal. Default is 1.
*normalize*:
Either False or the highest value among emotions. If not False, must normalize all petal lengths.
"""
if normalize:
emotion_score /= normalize
# Computing proportions.
h = 1*emotion_score + offset
x = height_width_ratio*emotion_score
y = h/2
r = sqrt(x**2 + y**2)
# Computing rotated centers
x_right, y_right = _rotate_point((x, y), angle)
x_left, y_left = _rotate_point((-x, y), angle)
# Circles and intersection
right = sg.Point(x_right, y_right).buffer(r)
left = sg.Point(x_left, y_left).buffer(r)
petal = right.intersection(left)
# alpha and color
alpha = 1 if highlight == 'regular' else .8
ecol = (colors.to_rgba(color)[0], colors.to_rgba(color)[1], colors.to_rgba(color)[2], alpha)
ax.add_patch(descartes.PolygonPatch(petal, fc=(0, 0, 0, 0), ec = ecol, lw= 1))
def _petal_shape_emotion(ax, emotion_score, color, angle, font, fontweight, fontsize, highlight, will_circle, offset = .15, height_width_ratio = 1, normalize = False):
"""
Draw a petal.
A petal is the intersection area between two circles.
The height of the petal depends on the radius and the center of the circles.
Full details at http://www.github.com/alfonsosemeraro/plutchik/tutorial.ipynb
Required arguments:
----------
*ax*:
Axes to draw the coordinates.
*emotion_score*:
Score of the emotion. Values range from 0 to 1.
*color*:
Color of the petal. See emo_params().
*angle*:
Rotation angle of the petal. See emo_params().
*font*:
Font of text. Default is Montserrat.
*fontweight*:
Font weight of text. Default is light.
*fontsize*:
Font size of text. Default is 15.
*highlight*:
String. 'opaque' if the petal must be shadowed, 'regular' is default.
*will_circle*:
Boolean. If three intensities will be plotted, then the lower petal must be pale.
*offset*:
Central neutral circle has radius = .15, and petals must start from there.
*height_width_ratio*:
Ratio between height and width of the petal. Lower the ratio, thicker the petal. Default is 1.
*normalize*:
Either False or the highest value among emotions. If not False, must normalize all petal lengths.
Returns:
----------
*petal*:
The petal, a shapely shape.
"""
if normalize:
emotion_score /= normalize
# Computing proportions.
h = 1*emotion_score + offset
x = height_width_ratio*emotion_score
y = h/2
r = sqrt(x**2 + y**2)
# Computing rotated centers
x_right, y_right = _rotate_point((x, y), angle)
x_left, y_left = _rotate_point((-x, y), angle)
# Circles and intersection
right = sg.Point(x_right, y_right).buffer(r)
left = sg.Point(x_left, y_left).buffer(r)
petal = right.intersection(left)
# Alpha for highlighting
if highlight == 'regular':
if will_circle:
alpha = .3
else:
alpha = .5
elif will_circle:
alpha = .0
else:
alpha = .0
ax.add_patch(descartes.PolygonPatch(petal, fc='white', lw = 0, alpha=1, zorder = 0))
ax.add_patch(descartes.PolygonPatch(petal, fc=color, lw= 0, alpha=alpha, zorder = 10))
return petal
def _petal_shape_dyad(ax, emotion_score, colorA, colorB, angle, font, fontweight, fontsize, highlight, will_circle, offset = .15, height_width_ratio = 1, normalize = False):
"""
Draw a petal.
A petal is the intersection area between two circles.
The height of the petal depends on the radius and the center of the circles.
Full details at http://www.github.com/alfonsosemeraro/plutchik/tutorial.ipynb
Required arguments:
----------
*ax*:
Axes to draw the coordinates.
*emotion_score*:
Score of the emotion. Values range from 0 to 1.
*colorA*:
First color of the petal. See dyad_params().
*colorB*:
Second color of the petal. See dyad_params().
*angle*:
Rotation angle of the petal. See dyad_params().
*font*:
Font of text. Default is Montserrat.
*fontweight*:
Font weight of text. Default is light.
*fontsize*:
Font size of text. Default is 15.
*highlight*:
String. 'opaque' if the petal must be shadowed, 'regular' is default.
*will_circle*:
Boolean. If three intensities will be plotted, then the lower petal must be pale.
*offset*:
Central neutral circle has radius = .15, and petals must start from there.
*height_width_ratio*:
Ratio between height and width of the petal. Lower the ratio, thicker the petal. Default is 1.
*normalize*:
Either False or the highest value among emotions. If not False, must normalize all petal lengths.
Returns:
----------
*petal*:
The petal, a shapely shape.
"""
if emotion_score == 0:
return ax
if normalize:
emotion_score /= normalize
# Computing proportions.
h = 1*emotion_score + offset
x = height_width_ratio*emotion_score
y = h/2
r = sqrt(x**2 + y**2)
# Computing rotated centers
x_right, y_right = _rotate_point((x, y), angle)
x_left, y_left = _rotate_point((-x, y), angle)
# Circles and intersection
right = sg.Point(x_right, y_right).buffer(r)
left = sg.Point(x_left, y_left).buffer(r)
petal = right.intersection(left)
# Computing squares: left
A = _rotate_point((-2*x, 0), angle)
B = _rotate_point((-2*x, h), angle)
C = _rotate_point((0, h), angle)
D = _rotate_point((0, 0), angle)
square_left = sg.Polygon([A, B, C, D, A])
# Computing squares: right
A = _rotate_point((0, 0), angle)
B = _rotate_point((0, h), angle)
C = _rotate_point((2*x, h), angle)
D = _rotate_point((2*x, 0), angle)
square_right = sg.Polygon([A, B, C, D, A])
# Computing semipetals
petalA = petal.intersection(square_left)
petalB = petal.intersection(square_right)
# white petal underneath
ax.add_patch(descartes.PolygonPatch(petal, fc='white', lw = 0, alpha=1, zorder = 0))
# Draw each half-petal in alpha 0.7
alpha = .7
xs, ys = petalA.exterior.xy
ax.fill(xs, ys, alpha=alpha, fc= colorA, ec='none')
xs, ys = petalB.exterior.xy
ax.fill(xs, ys, alpha=alpha, fc=colorB, ec='none')
return ax
def _petal_spine_emotion(ax, emotion, emotion_score, color, angle, font, fontweight, fontsize, highlight = 'all', offset = .15):
"""
Draw the spine beneath a petal, and the annotation of emotion and emotion's value.
The spine is a straight line from the center, of length 1.03.
Full details at http://www.github.com/alfonsosemeraro/plutchik/tutorial.ipynb
Required arguments:
----------
*ax*:
Axes to draw the coordinates.
*emotion*:
Emotion's name.
*emotion_score*:
Score of the emotion. Values range from 0 to 1. if list, it must contain 3 values that sum up to 1.
*color*:
Color of the petal. See emo_params().
*angle*:
Rotation angle of the petal. See emo_params().
*font*:
Font of text. Default is Montserrat.
*fontweight*:
Font weight of text. Default is light.
*fontsize*:
Font size of text. Default is 15.
*highlight*:
String. 'opaque' if the petal must be shadowed, 'regular' is default.
*offset*:
Central neutral circle has radius = .15, and petals must start from there.
"""
# Diagonal lines and ticks
step = .03
p1 = (0, 0)
p2 = _rotate_point((0, 1 + step + offset), angle) # draw line until 0, 1 + step + offset
p3 = _rotate_point((-step, 1 + step + offset), angle) # draw tick
ax.plot([p1[0], p2[0]], [p1[1], p2[1]], zorder = 5, color = 'black', alpha = .3, linewidth = .75)
ax.plot([p2[0], p3[0]], [p2[1], p3[1]], zorder = 5, color = 'black', alpha = .3, linewidth = .75)
# Managing highlighting and transparency
if highlight == 'opaque':
alpha = .8
color = 'lightgrey'
else:
alpha = 1
# Checking if iterable
try:
_ = emotion_score[0]
iterable = True
except:
iterable = False
if iterable:
# Label
angle2 = angle + 180 if -110 > angle > -260 else angle
p4 = _rotate_point((0, 1.40 + step + offset), angle)
ax.annotate(emotion, xy = p4, rotation = angle2, ha='center', va = 'center',
fontfamily = font, size = fontsize, fontweight = fontweight)
# Score 1
p5 = _rotate_point((0, 1.07 + step + offset), angle)
ax.annotate("{0:.2f}".format(round(emotion_score[0],2)), xy = p5, rotation = angle2, ha='center', va = 'center',
color = color, fontfamily = font, size = fontsize, fontweight = 'regular', alpha = alpha)
# Score 2
p6 = _rotate_point((0, 1.17 + step + offset), angle)
ax.annotate("{0:.2f}".format(round(emotion_score[1],2)), xy = p6, rotation = angle2, ha='center', va = 'center',
color = color, fontfamily = font, size = fontsize, fontweight = 'demibold', alpha = alpha)
# Score 3
p7 = _rotate_point((0, 1.27 + step + offset), angle)
ax.annotate("{0:.2f}".format(round(emotion_score[2],2)), xy = p7, rotation = angle2, ha='center', va = 'center',
color = color, fontfamily = font, size = fontsize, fontweight = 'regular', alpha = alpha)
else:
# Label
angle2 = angle + 180 if -110 > angle > -260 else angle
p4 = _rotate_point((0, 1.23 + step + offset), angle)
ax.annotate(emotion, xy = p4, rotation = angle2, ha='center', va = 'center',
fontfamily = font, size = fontsize, fontweight = fontweight)
# Score
p5 = _rotate_point((0, 1.1 + step + offset), angle)
ax.annotate("{0:.2f}".format(round(emotion_score,2)), xy = p5, rotation = angle2, ha='center', va = 'center',
color = color, fontfamily = font, size = fontsize, fontweight = 'demibold', alpha = alpha)
def _petal_spine_dyad(ax, dyad, dyad_score, color, emotion_names, angle, font, fontweight, fontsize, highlight = 'all', offset = .15):
"""
Draw the spine beneath a petal, and the annotation of dyad and dyad's value.
The spine is a straight line from the center, of length 1.03.
Full details at http://www.github.com/alfonsosemeraro/plutchik/tutorial.ipynb
Required arguments:
----------
*ax*:
Axes to draw the coordinates.
*dyad*:
Dyad's name.
*dyad_score*:
Score of the dyad. Values range from 0 to 1. if list, it must contain 3 values that sum up to 1.
*color*:
Color of the two emotions of the dyad. See dyad_params().
*emotion_names*:
Name of the emotions the dyad is made of. See dyad_params().
*angle*:
Rotation angle of the petal. See dyad_params().
*font*:
Font of text. Default is Montserrat.
*fontweight*:
Font weight of text. Default is light.
*fontsize*:
Font size of text. Default is 15.
*highlight*:
String. 'opaque' if the petal must be shadowed, 'regular' is default.
*offset*:
Central neutral circle has radius = .15, and petals must start from there.
"""
# Diagonal lines and ticks
step = .03
p1 = (0, 0) # 0, 0 + offset
p2 = _rotate_point((0, 1 + step + offset), angle) # draw line until 0, 1 + step + offset
p3 = _rotate_point((-step, 1 + step + offset), angle) # draw tick
ax.plot([p1[0], p2[0]], [p1[1], p2[1]], zorder = 5, color = 'black', alpha = .3, linewidth = .75)
ax.plot([p2[0], p3[0]], [p2[1], p3[1]], zorder = 5, color = 'black', alpha = .3, linewidth = .75)
# Managing highlighting and opacity
if highlight == 'opaque':
alpha = .8
color = 'lightgrey'
else:
alpha = 1
## Drawing the two-colored circular arc over dyads
from matplotlib.patches import Arc
H = 3.2
pac1 = Arc((0, 0), width = H, height = H, angle = 90, theta2 = angle, theta1 = angle - 18, ec = color[1], linewidth = 3)
pac2 = Arc((0, 0), width = H, height = H, angle = 90, theta2 = angle + 18, theta1 = angle, ec = color[0], linewidth = 3)
ax.add_patch(pac1)
ax.add_patch(pac2)
# Labels over the arcs
angle2 = angle + 180 if -110 > angle > -260 else angle
p9 = _rotate_point((0, 1.7), angle - 9)
ax.annotate(emotion_names[1], xy = p9, rotation = angle2 - 8, ha='center', va = 'center', zorder = 30,
fontfamily = font, size = fontsize * .7, fontweight = 'demibold', color = color[1])
p10 = _rotate_point((0, 1.7), angle + 9)
ax.annotate(emotion_names[0], xy = p10, rotation = angle2 + 8, ha='center', va = 'center', zorder = 30,
fontfamily = font, size = fontsize * .7, fontweight = 'demibold', color = color[0])
# Dyad label must be grey
color = '#363636'
# Label
angle2 = angle + 180 if -110 > angle > -260 else angle
p4 = _rotate_point((0, 1.23 + step + offset), angle)
ax.annotate(dyad, xy = p4, rotation = angle2, ha='center', va = 'center',
fontfamily = font, size = fontsize, fontweight = fontweight)
# Score
p5 = _rotate_point((0, 1.1 + step + offset), angle)
ax.annotate("{0:.2f}".format(round(dyad_score,2)), xy = p5, rotation = angle2, ha='center', va = 'center',
color = color, fontfamily = font, size = fontsize, fontweight = 'demibold', alpha = alpha)
def _petal_circle(ax, petal, radius, color, inner = False, highlight = 'none', offset = .15, normalize = False):
"""
Each petal may have 3 degrees of intensity.
Each of the three sections of a petal is the interception between
the petal and up to two concentric circles from the origin.
This function draws one section.
Full details at http://www.github.com/alfonsosemeraro/plutchik/tutorial.ipynb
Required arguments:
----------
*ax*:
Axes to draw the coordinates.
*petal*:
The petal shape. See petal().
*radius*:
Radius of the section.
*color*:
Color of the section. See emo_params().
*inner*:
Boolean. If True, a second patch is drawn with alpha = 0.3, making the inner circle darker.
*highlight*:
String. 'opaque' if the petal must be shadowed, 'regular' is default.
*offset*:
Central neutral circle has radius = .15, and petals must start from there.
*normalize*:
Either False or the highest value among emotions. If not False, must normalize all petal lengths.
"""
if radius:
if normalize:
radius /= normalize
# Define the intersection between circle c and petal
c = sg.Point(0, 0).buffer(radius + offset)
area = petal.intersection(c)
# Managing alpha and color
alpha0 = 1 if highlight == 'regular' else .2
ecol = (colors.to_rgba(color)[0], colors.to_rgba(color)[1], colors.to_rgba(color)[2], alpha0)
alpha1 = .5 if highlight == 'regular' else .0
# Drawing separately the shape and a thicker border
ax.add_patch(descartes.PolygonPatch(area, fc=color, ec = 'black', lw = 0, alpha=alpha1))
ax.add_patch(descartes.PolygonPatch(area, fc=(0, 0, 0, 0), ec = ecol, lw = 1.3))
# The innermost circle gets to be brighter because of the repeated overlap
# Its alpha is diminished to avoid too much bright colors
if inner:
alpha2 = .3 if highlight == 'regular' else .0
ax.add_patch(descartes.PolygonPatch(area, fc=color, ec = 'w', lw = 0, alpha=alpha2))
ax.add_patch(descartes.PolygonPatch(area, fc=(0, 0, 0, 0), ec = ecol, lw = 1.5))
def _draw_emotion_petal(ax, emotion, emotion_score, highlight_emotions, show_intensity_labels, font, fontweight, fontsize, show_coordinates, height_width_ratio, normalize = False):
"""
Draw the petal and its possible sections.
Full details at http://www.github.com/alfonsosemeraro/plutchik/tutorial.ipynb
Required arguments:
----------
*ax*:
Axes to draw the coordinates.
*emotion*:
Emotion's name.
*emotion_score*:
Score of the emotion. Values range from 0 to 1.
*highlight_emotions*:
A list of main emotions to highlight. Other emotions will be shadowed.
*show_intensity_labels*:
A string or a list of main emotions. It shows all three intensity scores for each emotion in the list, and for the others cumulative scores. Default is 'none'.
*font*:
Font of text. Default is Montserrat.
*fontweight*:
Font weight of text. Default is light.
*fontsize*:
Font size of text. Default is 15.
*offset*:
Central neutral circle has radius = .15, and petals must start from there.
*show_coordinates*:
A boolean, wether to show polar coordinates or not.
*normalize*:
Either False or the highest value among emotions. If not False, normalize petal length.
"""
color, angle, _ = emo_params(emotion)
# Check if iterable
try:
_ = emotion_score[0]
iterable = True
except:
iterable = False
# Manage highlight and opacity
if highlight_emotions != 'all':
if emotion in highlight_emotions:
highlight = 'regular'
else:
highlight = 'opaque'
else:
highlight = 'regular'
if not iterable:
if show_coordinates:
# Draw the line and tick behind a petal
_petal_spine_emotion(ax = ax, emotion = emotion, emotion_score = emotion_score,
color = color, angle = angle,
font = font, fontweight = fontweight, fontsize = fontsize,
highlight = highlight,
offset = .15)
# Draw petal