Wednesday, September 30, 2009

Really Cool R Graphic

Really cool R Graphic
Recently I needed to make a funky graphic-table combo in R. Here's the challenge - To combine a vertical bar chart and the data table in a single graphic.

As much as I like R, it's graphics systems are mind-bogglingly complex. You have the base graphics system PLUS Lattice, ggplot, iplot, etc. There are way too many graphics systems. I couldn't even figure out which one I should focus on learning.

When in doubt, turn to the appropriate forum. I posted some stuff on the R-Users mailing list and got a fantastic reply from a guy named Marc. View via Nabble.

I was able to take what he sent me, and learn from it. After playing around with it a little, I got the hang of it and I was able to adapt what he sent and use it for my project at work.

Below is the full version of what he sent me. There is further discussion about this here.

Enjoy!


#---------------------------------------------------------
# Create data
MyData <- matrix(c(57.1, 52.3, 13.5, 13.9, 7.9, 8.8, 5.4, 5.6, 16.1, 19.4), nrow = 2) # Note that by using '\n' in the text, the label will be plotted on # two lines. '\n' is a newline character colnames(MyData) <- c("0 occasions", "1-2 Occasions", "3-5 Occasions", "6-9 Occasions", "10 or more\nOccasions") rownames(MyData) <- c("Androscoggin", "Maine") > MyData
0 occasions 1-2 Occasions 3-5 Occasions 6-9 Occasions
Androscoggin 57.1 13.5 7.9 5.4
Maine 52.3 13.9 8.8 5.6
10 or more\nOccasions
Androscoggin 16.1
Maine 19.4


# Set graph margins to make room for labels
# See ?par
par(mar = c(5, 8, 4, 1))


# Set colors
MyCols <- c("black", "grey80") # Set label size MyCex = 0.75 # Set lines for table data MyLines <- 2:3 # do barplot, getting bar midpoints in 'mp' # See ?barplot mp <- barplot(MyData, beside = TRUE, ylim = c(0, 100), yaxt = "n", cex.names = MyCex, col = MyCols) # mp contains the following. The mean of each column # is the horizontal center of each pair of bars > mp
[,1] [,2] [,3] [,4] [,5]
[1,] 1.5 4.5 7.5 10.5 13.5
[2,] 2.5 5.5 8.5 11.5 14.5


# Put a box around it
box()


# Draw y axis tick marks and labels
axis(2, at = seq(0, 100, 10), las = 1)


# Draw values below plot
# Use the values of 'mp' from above.
# See ?mtext
mtext(side = 1, text = MyData,
at = rep(colMeans(mp), each = nrow(MyData)),
line = MyLines, cex = MyCex)


# Get min value for the x axis. See ?par 'usr'
min.x <- par("usr")[1]


# Draw categories using mtext
# See ?strwidth to get the length of the labels in
# user coordinates, which is then used for 'at'
# Setting 'adj = 0' left justifies the text
mtext(side = 1, line = MyLines, text = rownames(MyData),
at = min.x - max(strwidth(rownames(MyData), cex = MyCex)),
adj = 0, cex = MyCex)


# Draw the colored boxes
# Same here for strheight as with strwidth above
# Part of this is getting the vertical positioning to align with
# the text and the horizontal position at the beginning of the labels
# Note that we have to set 'xpd = TRUE' so that the points are drawn
# outside the plotting region. See ?par and 'xpd'
# We just need a single capital letter for strheight() to get the value

VertOff <- strheight("X", cex = MyCex) * c(6, 8)
HorizOff <- min.x - (0.85 * max(strwidth(rownames(MyData))))

points(rep(HorizOff, nrow(MyData)),
par("usr")[3] - VertOff, bg = MyCols, pch = 22,
xpd = TRUE, cex = MyCex)

# --------------------------------------------------------------------------------------------

Saturday, September 12, 2009

Gun control is a complicated issue. It is too often dumbed down into 10 irrelevant talking points that have nothing to do with the situation on the ground. Unfortunately, this is not unlike many other political discussions in our society. The talking points from the previous post are easy for people to understand (mis-interpret) and are used to convey a message that is largely at odds with reality. Let me be clear. I fully respect people's right and intellectual ability to look at a set of facts and come to a conclusion different than my own. What I do not respect is the accumulation of "facts" which are clearly cherry-picked and manipulated to present a facade, rather than the grounds for vigorous debate.

The data provided by my friend is irrelevant to a discussion based on reality. I will divide this discussion into two parts, because there were two different types of misinformation in the "facts" sent to me. Many of the facts concern disarming various minority groups by a repressive regime. The rest present a set of facts, that lack the broader historical/political/economic context. Information does not exist in a vacuum. It fits into a context. When we ignore the context, it becomes impossible to know whether or not the facts are useful.

Most of the facts are historical examples from other countries. These facts rely on things that happened years ago in countries most Americans know little about. They also focus on various repressive regimes taking guns away from minority groups which had been long repressed by the local majorities. This makes the parallel to today's politics irrelevant unless you are simultaneously arguing that the American government is planning on repressing us (gun-owners). The majority of legal gun-owners (I include myself in this group) in this country are white males. Have you looked at Congress lately? They are overwhelmingly both White and Male. I find it unlikely that a government composed of middle-class (read rich as hell) White men is intent of persecuting me, a White male. I would instead posit that this selection of facts has more to do with creating an atmosphere of fear/distrust than it does in providing reasonable grounds for discussion.

It is also interesting (amusing) that American History is completely ignored in these facts. Historical facts are more dangerous when everyone understands the broader context of the discussion. It's easier to have talking points that people don't understand, rather than talking points that people can actually challenge you on. It's a debating trick that I am personally quite fond of although it is a little under- handed. In this case I will try to apply some lessons from our own history to set the record straight(er).

The US government actively disarmed Native Americans during the 1800's. Why? Simple greed. We (Americans) intended to persecute these peoples so Americans (mostly White) could take their land/gold/buffalo. It's easier to beat-up on unarmed native populations. My favorite example here would be the massacre at Wounded Knee. If you aren't familiar with this tragedy, look it up. Similarly, slaves (again, a minority group), were prohibited from owning anything that could be easily used as a weapon. You don't humiliate a grown man for every day of his life and then give him a gun unless you are suicidal. These two American examples are similar in nature to many of the facts presented in the original email I am responding to. The people who are disarmed (or prevented from arming themselves in the first place) are a persecuted minority group. For example, the original facts referenced the tragedies which befell the Turkish Armenians, Ugandan Christians and Guatemalan Mayans. Comparing these tragedies with the situation faced by members of the NRA is both laughable and an insult to those who perished. I don't really see myself as a persecuted minority (and I have a Jewish last name). Rather than relying on sound-bites comparing Obama to Hitler, people need to accept that our government is unlikely to repress Americans in a manner similar to that faced by the Turkish Armenians or Native Americans.

Conveniently, there are other relevant facts from American History. Wyatt Earp, Doc Holiday, and several other Western Marshalls went down in pop- history because . . . . . . . . . wait for it . . . . . . . . . they unarmed
the Wild Wild West. You see, the Western Boom Towns had a problem. Every Tom, Dick, and Harry carried at least one gun. Carrying guns was clearly necessary in the vast expanses of country-side between these towns (we had not yet disarmed all of the Indians we were trying to repress), but in the Boom Towns these guns caused a lot of problems. The solution was to disarm, everyone, except the local law enforcement. In this example, the government (local) did not intend to repress anyone. The goal was to make the entire community safer. They couldn't close down all of the bars or prevent the cow-boys from getting rowdy, but they could make sure that people weren't shooting one another. Thus more people lived to carouse another day. This example seems especially apropos because of the problems we experience today. New York City, Washington
DC, etc. are all trying to respond to the problems inherent in having lots of guns in a community with lots of poverty, drinking, drug-abuse, etc.

Let's be clear about something. Americans ARE dieing and they are dieing because someone shot them with a gun. To pretend otherwise is ridiculous. It is equally true that suburban/rural Americans are not experiencing these problems. Life in South Central LA is very different from the lives of Americans going down to the mall in suburban America. I believe this divide is the fundamental source of the tension in this debate. Upper-class Americans (suburbia) and rural Americans are not dieing on a regular basis due to gun-fire. But urban areas like Albany, NY are experiencing these problems every single day. Albany alone has experienced multiple shooting fatalities this summer involving adults, children, men and women. No citizen is truly safe in the West End (ghetto) of Albany but citizens in Guilderland (suburb) are. Unfortunately, I see very little public discussion about this tension from the left or the right. An policy discussion that fails to address this tension is doomed to fail and the consequences are as immediate as they are tragic.

When the talking points rely heavily on historical examples where disarmament is followed by repression, there is an often unspoken rationale. These groups want to encourage people's distrust in our government. This is especially true when there is a Democrat in the White House. Fear mongering is always good for a quick sound-byte. Think about it. How many of these sorts of forwards and discussions did you see during the Bush Administration? Yet, Bush's policies of spying on Americans and creating loop-holes around Habeas Corpus actively infringed on our Constitutional Rights (although not Amendment 2). I don't remember any conservatives out in the streets beating their drums when this happened. The complaints now are classical political opportunism. The conservative machine is very savvy politically. It knows that gun-control is a hot-button issue for many Americans. Remember that tension I pointed out?) It's not in their best interest to fuel a real discussion. It's easier and better politically to get everyone . . . up in arms (sorry, I had to use the phrase) . . . over this stuff. The Obama administration has not once suggested about gun-control, but here we are sending having a discussion based on carefully selected points that have more to do with scaring people shitless than it does with providing information to empower individuals to participate in a policy discussion.

Now, let's look at some other quick facts. Yep. Washington DC and New York City both have some of the strictest gun-control rules in the nation. Interestingly, they have had different results. New York City today is actually much safer than it was in the 80's at the height of the Crack Epidemic. Additional police resources, gun-control and other measures have made it difficult for NYC gangs to get guns, which in turn limits how many idiots on the street are packing illegal heat. Ironically, our nation's capital has not been as successful. But, I find it interesting that L.A. was ignored. Here is a sprawling metropolis where buying a hand-gun may actually be as easy as buying an ice-cream cone. In L.A., gang-warfare, yes, warfare is a way of life. The Finger Lakes in upstate NY will never (I pray) experience gang-warfare. In L.A. it's a daily way of life. Arguing that guns aren't part of the problem in South Central L.A. isn't useful. Guns are part of the problem. Of course they aren't the entire problem, but cute sound-bytes like this:

"Guns, don't kill people, people kill people."

is an insulting thing to say when American citizens (just like you and I) are mowing each other down in a haze bullets. The pursuit of life liberty and the pursuit of happiness (property) is an empty dream when guns deprive you of that same life. Yet, I recently saw a guy on TV wearing a shirt that said guns aren't the problem (see above).

As a citizen of an urban area that struggles with gun violence on a regular basis (Albany, NY) I also recognize another important fact that must be recognized and acknowledged to find policies that will address the fundamental problem. The shooters and their victims are not NRA members. They are not hunters (with the rare, tragic exception). They are children, teens, and adults living in densely packed urban centers. Last time I checked, the NRA had not run a successful recruitment campaign here in down-town Albany, although there are many many gun-owners. The NRA isn't interested in these gun-owners because the guns are illegal and the owners really should not be owning or handling fire-arms. They are not responsible gun-owners and they are rarely model citizens. As with many other things, lumping everyone who shares a common trait into one big pile is rarely a good idea. Gun-owners are no different.

Returning to the "facts" from the email. . . . If we are going to have a discussion that includes examples from other countries that Americans may or may not really understand, I would also suggest Mexico and Colombia. Neither country has meaningful gun- control. It's easy to get a gun. Anyone can get one. Sadly, the end result has not been a utopia. In a manner than looks a lot like South Central LA, people are dying in droves from lead poisoning. I could also suggest that you look at German gun-control laws. These are considered some of the tightest laws in Europe. Here is an excerpt from the US State department website to Americans thinking about traveling to Germany:

CRIME: Violent crime is rare in Germany, but can occur, especially in larger cities or high-risk areas such as train stations. Most incidents of street crime consist of theft of unattended items and pick-pocketing.

This is what the same state department says about Switzerland, which has a very different out-look on gun-control.

CRIME: Switzerland has a low rate of violent crime. However, pick-pocketing and purse snatching do occur in the vicinity of train and bus stations, airports, and some public parks, especially during peak tourist periods (such as Summer and Christmas) and when conferences, shows, or exhibits are scheduled in major cities.

Do you see any similarities? When traveling in either country, tourists should be concerned about pick-pockets! Now, it should be noted that Germany does actually have a higher crime rate than Switzerland. Although most of that crime is concentrated in what was once the Soviet Bloc. If you compare Western Germany to Switzerland, you will discover that the statistics are very very similar. This highlights an important point. It is inappropriate to use examples from another country unless those examples are well understood.

Anti-gun-control activists often point to Switzerland's policies and (inappropriately) conclude that the low-crime is a result of these gun-control policies. To be blunt, that is a shallow fabrication. Equally shallow is an argument that access to guns inevitably leads to violence. Crime statistics MUST be assessed in a broader context. Switzerland is an overwhelmingly middle-class country. In fact, it has a larger middle class (as a proportion of the population) than we do. It also has a much stronger social safety net than our own - something Americans would call socialism. In discussing Switzerland's low crime rate, ignoring these two factors is truly disingenuous.

Equally disingenuous is my use of Mexico and Colombia as examples where gun- control is essentially nil, and yet violent crime is high. It's inappropriate because many of the guns on the street are paid for (lock, stock and all smoking barrels) by the American government/American tax-payers as part of our war on drugs. Yep. Those Colombian para-military death-squads use guns that are often paid for by Uncle Sam. Many of the other guns are purchased from American gun manufacturers, thus our economy actually profits from the insanity. But, here's the important lesson. These facts are essentially useless. Just like the naked numbers from Switzerland don't help us understand their meaning, my cherry-picked facts about Mexico and Colombia are misleading garbage. There are other things that contribute to the violence in those countries. Both countries are also comparatively poor and have small middle classes (among other issues). In fact, I would argue that violent crime statistics are more closely tied to the size of the middle class (this is an over-simplification, but fine for right now) than it is to any gun-control policy.

So here we are. I've wasted a bit of time writing this and you've wasted a little bit of time reading it. Americans are still shooting one another in the streets of LA and red-necks in Georgia are still talking trash about the low-
crime rate in Switzerland. The former is tragic while the latter is actually quite humorous. What has this taught us? Probably not much. In order to make REAL progress on an issue like gun-control or health care we need to talk to one another. We need to take these bullshit talking points (and the bullshitters who propagate them) and put them into time-out or possibly the bottom of the ocean (concrete shoes are nice). Once we do that, we can actually sit down as a nation and talk about the real issues here. A real solution will require us, as a nation, to balance the needs of urban population centers (like NYC, and Boom Towns like Dodge) with the needs and desires of suburbia and rural America. Yes, the Constitution must be respected, but so must we respect the lives of the people dieing in the violence that is consuming parts of the nation. But, we can't do that as long as we rely on shallow comparisons to a middle-class country better known for it's lederhosen than for it's gun-control laws.

Gun Control?

I recently received an email from a friend full of "facts" to show why gun control is not necessary. I was surprised, and disappointed when I saw this.
First I will post what my friend sent me. The next post will be my reply. Note: While I did remove the formatting, I did not modify the content.


A Gun History
After reading the following historical facts, read the part about Switzerland twice.

A LITTLE GUN HISTORY

  1. In 1929, the Soviet Union established gun control.. From 1929 to 1953, about 20 million dissidents, unable to defend themselves, were rounded up and exterminated.
  2. In 1911, Turkey established gun control. From 1915 to 1917, 1.5 million Armenians, unable to defend themselves, were rounded up and exterminated.
  3. Germany established gun control in 1938 and from 1939 to 1945, a total of 13 million Jews and others who were unable to defend themselves were rounded up and exterminated.
  4. China established gun control in 1935. From 1948 to 1952, 20 million political dissidents, unable to defend themselves, were rounded up and exterminated.
  5. Guatemala established gun control in 1964. From 1964 to 1981, 100,000 Mayan Indians, unable to defend themselves, were rounded up and exterminated.
  6. Uganda established gun control in 1970. From 1971 to 1979, 300,000 Christians, unable to defend themselves, were rounded up and exterminated.
  7. Cambodia established gun control in 1956. From 1975 to 1977, one million educated people, unable to defend themselves, were rounded up and exterminated.
  8. Defenseless people rounded up and exterminated in the 20th Century because of gun control: 56 million.
  9. It has now been 12 months since gun owners in Australia were forced by new law to surrender 640,381 personal firearms to be destroyed by their own Government, a program costing Australia taxpayers more than $500 million dollars. The first year results are now in:
List of 7 items:
  1. Australia-wide, homicides are up 3.2 percent.
  2. Australia-wide, assaults are up 8.6 percent.
  3. Australia-wide, armed robberies are up 44 percent (yes, 44 percent)!
  4. In the state of Victoria alone, homicides with firearms are now up 300 percent. Note that while the law-abiding citizens turned them in, the criminals did not, and criminals still possess their guns!
  5. While figures over the previous 25 years showed a steady decrease in armed robbery with firearms, this has changed drastically upward in the past 12 months, since criminals now are guaranteed that their prey is unarmed.
  6. There has also been a dramatic increase in break-ins and assaults of the ELDERLY. Australian politicians are at a loss to explain how public safety has decreased, after such monumental effort, and expense was expended in successfully ridding Australian society of guns. The Australian experience and the other historical facts above prove it.
  7. You won't see this data on the US evening news, or hear politiciansdisseminating this information.
Guns in the hands of honest citizens save lives and property and, yes,
gun-control laws adversely affect only the law-abiding citizens. Take note my fellow Americans, before it's too late! The next time someone talks in favor of gun control, please remind them
of this history lesson. With guns, we are 'citizens.' Without them, we are 'subjects'. During WWII the Japanese decided not to invade America because they knew most Americans were ARMED!

Communist Doctrine says that they must DISARM the Population, before they can dominate them!
If you value your freedom, please spread this anti-gun control message to all of your friends.

The purpose of fighting is to win. There is no possible victory in defense. The sword is more important than the shield, and skill is more important than either. The final weapon is the brain. All else is supplemental.

SWITZERLAND ISSUES EVERY HOUSEHOLD A GUN! AND They Train every Adult that they issue a Rifle
SWITZERLAND HAS THE LOWEST GUN RELATED CRIME RATE OF ANY CIVILIZED COUNTRY IN THE WORLD!!!

IT'S A NO BRAINER! DON'T LET OUR GOVERNMENT WASTE MILLIONS OF OUR TAX DOLLARS IN AN EFFORT TO MAKE ALL LAW ABIDING CITIZENS AN EASY TARGET.

I'm a firm believer of the 2nd Amendment! If you are too, please forward. Just think how powerful our government is getting! They are out of Control! They think these other countries just didn't do it right.
We MUST keep our Constitution and especially the 1st and 2nd Amendments INTACT! Don't let them take it away from us!!! Learn from history.

FOOTNOTE: NYC & WASHINGTON, DC HAVE HAD STRICT GUN CONTROL LAWS FOR MANY YEARS. THEY ARE 2 OF THE HIGHEST CRIME RIDDEN CITIES IN AMERICA. ANY IDEA WHY