from paws.TweetsFactsAndQueries.embedWDQS import wdqsWidget, WDQSView

The ?rgb variable in WDQS

One lesser-known feature of WDQS is that several result views support setting a variable to control the color in the view.

For example, this query finds the most common eye colors on Wikidata (source):

query="""
SELECT ?eyeColorLabel (COUNT(?person) AS ?count)
WHERE
{
  ?person wdt:P1340 ?eyeColor.
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}
GROUP BY ?eyeColorLabel
"""
wdqsWidget(query, view=WDQSView.BubbleChart)

But the bubbles are colored randomly; the “blue” bubble may in fact be green, or orange, or some other color. We can fix that: if the results contain a variable ?rgb, and the value in that variable looks like an HTML RGB color code (i. e., six hex digits), the bubble chart uses that color for the bubble. We can get such a color code from the “sRGB color hex triplet” property (query source):

query2="""
SELECT ?eyeColorLabel (SAMPLE(?rgb) AS ?rgb) (COUNT(DISTINCT ?person) AS ?count)
WHERE
{
  ?person wdt:P1340 ?eyeColor.
  OPTIONAL { ?eyeColor wdt:P462?/wdt:P465 ?rgb. }
  BIND(IF(BOUND(?rgb),?rgb,"CCCCCC") AS ?rgb).
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}
GROUP BY ?eyeColorLabel
"""
wdqsWidget(query2, view=WDQSView.BubbleChart)

Some bubbles are now light grey – I chose that color ("CCCCCC") as default if no “sRGB color hex triplet” statement is available.

But the bubble view is not the only one to support this feature: the graph view does too! This can be used to color-code two kinds of nodes, as in this query by Andra Waagmeester (source) that shows diseases (orange) and drugs used to treat them (green):

query3="""
SELECT DISTINCT ?item ?itemLabel ?rgb ?link
WHERE
{
  VALUES ?toggle { true false }
  ?disease wdt:P699 ?doid;
           wdt:P279+ wd:Q18123741;
           wdt:P2176 ?drug.
  ?drug rdfs:label ?drugLabel.
  FILTER(LANG(?drugLabel) = "en").
  ?disease rdfs:label ?diseaseLabel.
  FILTER(LANG(?diseaseLabel) = "en").
  BIND(IF(?toggle,?disease,?drug) AS ?item).
  BIND(IF(?toggle,?diseaseLabel,?drugLabel) AS ?itemLabel).
  BIND(IF(?toggle,"FFA500","7FFF00") AS ?rgb).
  BIND(IF(?toggle,"",?disease) AS ?link).
}
"""
wdqsWidget(query3, view=WDQSView.Graph)