I have two lists, that have the same elements but in different order.
foo = ["A", "B", "C", "D", "E", "F"]
bar = ["C", "A", "B", "D", "E", "F"]
Now, I want to know which elements that were swapped and present that in a plot, with some visual clues to make it easier to spot the shuffling.
The plot should have colored lines between the diffing elements. Something like this below, but with colors and in matplotlib.
A B C D E F
v---\---\--^
C A B D E F
As a start, this will list all the items that are not mapped to the same value
for f, b, in zip(foo, bar):
if f != b:
print(f, b)
Expanding on alphanimals example for finding positions, you can use annotate to indicate the array positions, then use index to find the position of the swaps in the array.
Like the following example shows:
import matplotlib.pyplot as plt
foo = ["A", "B", "C", "D", "E", "F"]
bar = ["C", "A", "B", "D", "E", "F"]
# put data point names on plots
for num in range(len(bar)):
plt.annotate(bar[num], # this is the text
(num,1), # this is the point to label
textcoords="offset points", # how to position the text
xytext=(0,10), # distance from text to points (x,y)
ha='center') # horizontal alignment can be left, right or center
for num in range(len(foo)):
plt.annotate(foo[num], # this is the text
(num,2), # this is the point to label
textcoords="offset points", # how to position the text
xytext=(0,10), # distance from text to points (x,y)
ha='center') # horizontal alignment can be left, right or center
plt.plot(foo,len(foo)*[1],'bo-')
plt.plot(bar,len(bar)*[2],'bo-')
for f, b, in zip(foo, bar):
if f != b:
print(f,b)
bar_position = bar.index(f)
foo_position = foo.index(f)
swappositions = [bar_position,foo_position]
plt.plot(swappositions,[1,2],'r--') # indicates dashed red line for swapped elements
#turn off ticks
plt.tick_params(
axis='x', # changes apply to the x-axis
which='both', # both major and minor ticks are affected
bottom=False, # ticks along the bottom edge are off
top=False, # ticks along the top edge are off
labelbottom=False) # labels along the bottom edge are off
plt.show()
Yielding the following plot:
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.